首页 IT程序员内容详情

axios实现简单文件上传功能

2021-05-24 27445 编程艺术家

本文实例为大家分享了axios实现文件上传功能的具体代码,供大家参考,具体内容如下

前台页面:

引入axios js文件

1

HTML:

1
2
3
<input type="file" name="img"/>
<br>
<span οnclick="upload()">上传图片</span>

JS:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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);
 });
}

后台接收:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@PostMapping(value = "/upload")
public String upload(HttpServletRequest request){
 logger.info("开始上传……");
  
 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:

1
2
3
4
5
6
<!-- 文件上传 -->
<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3</version>
</dependency>

注入CommonsMultipartResolver:

1
2
3
4
5
6
7
@Bean
public CommonsMultipartResolver initCommonsMultipartResolver(){
 CommonsMultipartResolver resolver = new CommonsMultipartResolver();
 resolver.setMaxUploadSize(104857600);
 resolver.setMaxInMemorySize(4096);
 return resolver;
}


转载于:axios实现简单文件上传功能_javascript技巧_脚本之家 (jb51.net)

相关标签: # vue

 暂无评论,快来抢沙发吧~

发布评论