您好,登錄后才能下訂單哦!
本文實(shí)例為大家分享了axios實(shí)現(xiàn)文件上傳功能的具體代碼,供大家參考,具體內(nèi)容如下
前臺(tái)頁(yè)面:
引入axios js文件
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
HTML:
<input type="file" name="img"/> <br> <span οnclick="upload()">上傳圖片</span>
JS:
function upload() { alert("上傳") let file = document.getElementsByName('img')[0].files[0]; let formData = new FormData(); formData.append("uploadFile",file,file.name); const config = { headers: { "Content-Type": "multipart/form-data;boundary="+new Date().getTime() } }; axios .post("/file/upload",formData,config) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); }
后臺(tái)接收:
@PostMapping(value = "/upload") public String upload(HttpServletRequest request){ logger.info("開(kāi)始上傳……"); MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = servletRequest.getFileMap(); for (Map.Entry entry : fileMap.entrySet()) { logger.info("name : {}",entry.getKey()); MultipartFile multipartFile = (MultipartFile) entry.getValue(); try { FileUtil.writeFile(multipartFile.getInputStream(),path+"/12_"+multipartFile.getOriginalFilename()); } catch (IOException e) { e.printStackTrace(); } } return "{'result':'OK'}"; } @RequestMapping(value = "/uploadII") public String uploadII(@RequestParam("uploadFile") MultipartFile uploadFile){ logger.info("upload : {}",uploadFile); try { InputStream inputStream = uploadFile.getInputStream(); String originalFilename = uploadFile.getOriginalFilename(); logger.info("file : {}",originalFilename); FileUtil.writeFile(inputStream,path+"/"+originalFilename); } catch (IOException e) { e.printStackTrace(); } return "{'result':'OK'}"; }
pox.xml:
<!-- 文件上傳 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency>
注入CommonsMultipartResolver:
@Bean public CommonsMultipartResolver initCommonsMultipartResolver(){ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(104857600); resolver.setMaxInMemorySize(4096); return resolver; }
GitHub:axios
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。