前台:
<html> <head> <meta charset="utf-8"> <title></title> <script src="vue.js" type="text/javascript" charset="UTF-8"></script> <script src="jquery-3.6.0.js" type="text/javascript" charset="UTF-8"></script> </head> <body> <div id="app"> {{message}} <input type="file" name="file" id="file" @change=‘onUpload‘>//注意不能带括号 </div> </body> </html> <script type="text/javascript"> var vm = new Vue({ el: ‘#app‘, data: { message: ‘test‘, }, methods: { //上传图片 onUpload(e) { var formData = new FormData(); formData.append(‘file‘, e.target.files[0]); formData.append(‘type‘, ‘test‘); $.ajax({ // url: ‘/ShopApi/util/upload.weixun‘, url: ‘http://localhost:8083/order/process/upload‘, type: ‘POST‘, dataType: ‘json‘, cache: false, data: formData, processData: false, contentType: false, success: (res) => { if (res.code === 200) { alert(6) } }, error: function(err) { alert("网络错误"); } }); } } }); </script>
后台:
@PostMapping("/upload") public Object batchImportUpload(@RequestParam("file") MultipartFile uploadFile) throws IOException { log.info("在线批量导入req:"); // 另一种方法参考 // https://www.cnblogs.com/cheng2839/p/12660411.html //获取项目目录临时路径 String staticPath = ClassUtils.getDefaultClassLoader().getResource("mapper").getPath(); //生成临时目录 File tempfolder = new File(staticPath + "/uploadFile/"); if (!tempfolder.isDirectory()) { tempfolder.mkdirs(); } //源文件名 String oldName = uploadFile.getOriginalFilename(); //新文件名 String newName = System.currentTimeMillis() + oldName.substring(oldName.lastIndexOf(".")); File newFile = new File(tempfolder, newName); //填充新文件 uploadFile.transferTo(newFile); //新文件路径 String newFileAllName = tempfolder + "/" + newName; log.info("临时文件全路径:{}" + newFileAllName); return new Response(ResultCode.OK, newFileAllName); }