axios实现简单⽂件上传功能本⽂实例为⼤家分享了axios实现⽂件上传功能的具体代码,供⼤家参考,具体内容如下
前台页⾯:
引⼊axios js⽂件
<script src="unpkg/axios/dist/axios.min.js"></script>
HTML:
<input type="file" name="img"/>
<br>inputtypefile不上传文件
<span οnclick="upload()">上传图⽚</span>
JS:
function upload() {
alert("上传")
let file = ElementsByName('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);
});
}
后台接收:
@PostMapping(value = "/upload")
public String upload(HttpServletRequest request){
logger.info("开始上传……");
MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = FileMap();
for (Map.Entry entry : Set()) {
logger.info("name : {}",Key());
MultipartFile multipartFile = (MultipartFile) Value();
try {
FileUtil.InputStream(),path+"/12_"+OriginalFilename());
} 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 = InputStream();
String originalFilename = OriginalFilename();
logger.info("file : {}",originalFilename);
FileUtil.writeFile(inputStream,path+"/"+originalFilename);
} catch (IOException e) {
e.printStackTrace();
}
return "{'result':'OK'}";
}
<!-- ⽂件上传 -->
<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:
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论