本文实例为大家分享了Axios和Jquery实现文件上传的具体代码,供大家参考,具体内容如下
jquery文件时,后端好像并没有经过SpringMVC处理,没有被封装成一个MultiPartFIle对象,可通过原生的Servlet API request.getInputStream()获取。至于为什么没被SpringMVC封装成MultipartFile对象目前还没有研究透彻。可能是请求内容类型没有设置成 multipart/form-data。下面是jquery上传文件的代码示例,文件名,文件大小等参数可通过拼在url后面使用request.getParameter()获取。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="jquery.js"></script> <script src="axios.js"></script> <body> 请上传图片:<input type="file" name="file" id="file" onchange="fileChange(this)"> <br> <button onclick="jqueryUpload()">jquery提交</button> </body> <script> var file = undefined function fileChange(data){ file = data.files[0] } function jqueryUpload(){ $.ajax({ url:"/jqueryUpload?filename=test.jpg", type:"post", data:file, contentType:false, processData:false, success(res){ console.log('上传结果' + res) } }) } </script> </html>
@PostMapping("jqueryUpload") public String jqueryUpload(HttpServletRequest request, MultipartFile file) throws Exception{ System.out.println(file); String fileDesc = "D:\\2022\\" + request.getParameter("filename"); FileOutputStream outputStream = new FileOutputStream(fileDesc); ServletInputStream inputStream = request.getInputStream(); byte[] bytes = new byte[1024]; int line = inputStream.read(bytes); while (line != -1){ outputStream.write(bytes,0,line); line = inputStream.read(bytes); } inputStream.close(); outputStream.close(); return "success"; }
此时后台打印的multipartfile是null。后续会深入研究·······…
axios上传不同于jquery,axios将上传的二进制数据和其他参数封装在了FormData对象中,值得注意的是,此时的内容类型要改为multipart/form-data。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <script src="jquery.js"></script> <script src="axios.js"></script> <body> 请上传图片:<input type="file" name="file" id="file" onchange="fileChange(this)"> <br> <button onclick="jqueryUpload()">jquery提交</button> <button onclick="axiosUpload()">axios提交</button> </body> <script> var file = undefined function fileChange(data){ file = data.files[0] } function axiosUpload(){ var formData = new FormData(); formData.append("file",file); formData.append("filename","myfile.jpg") axios.post("/axiosUpload",formData,{ headers:{ "Content-Type" : "multipart/form-data" } }).then(res => { console.log('上传结果' + res) }) } </script> </html>
@PostMapping("axiosUpload") public String axiosUpload(HttpServletRequest request,MultipartFile file)throws Exception{ InputStream inputStream = file.getInputStream(); String fileDesc = "D:\\2022\\" + request.getParameter("filename"); FileOutputStream os = new FileOutputStream(fileDesc); byte[] bytes = new byte[1024]; int line = inputStream.read(bytes); while (line != -1){ os.write(bytes,0,line); line = inputStream.read(bytes); } inputStream.close(); os.close(); return "success"; }
感觉还是更喜欢axios这种,明确指定了内容类型并且经过了SpringMVC处理。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持插件窝。