axios实现简单文件上传功能
本文实例为大家分享了axios实现文件上传功能的具体代码,供大家参考,具体内容如下
站在用户的角度思考问题,与客户深入沟通,找到肥城网站设计与肥城网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都做网站、网站制作、企业官网、英文网站、手机端网站、网站推广、国际域名空间、雅安服务器托管、企业邮箱。业务覆盖肥城地区。
前台页面:
引入axios js文件
HTML:
上传图片
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); }); }
后台接收:
@PostMapping(value = "/upload") public String upload(HttpServletRequest request){ logger.info("开始上传……"); MultipartHttpServletRequest servletRequest = (MultipartHttpServletRequest) request; MapfileMap = 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:
commons-fileupload commons-fileupload 1.3
注入CommonsMultipartResolver:
@Bean public CommonsMultipartResolver initCommonsMultipartResolver(){ CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setMaxUploadSize(104857600); resolver.setMaxInMemorySize(4096); return resolver; }
GitHub:axios
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
分享名称:axios实现简单文件上传功能
分享路径:http://azwzsj.com/article/ipcspp.html