一、前台json
action 不用改 :https://jsonplaceholder.typicode.com/posts/app
getFile: 获取文件dom
data(){ return { file: {}, fileList: [] } } <el-upload action="https://jsonplaceholder.typicode.com/posts/" :file-list="fileList" @on-change="handleChange" :http-request="getFile" > <el-button size="small" type="primary">上传</el-button> </el-upload> <el-button size="small" type="success" @click="upload">确认上传</el-button>
getFile(item) { console.log(item.file) this.file = item.file }, upload() { const fd = new FormData() fd.append('filename', this.file) const config = { headers: { 'Content-Type': 'multipart/form-data' }} this.$request.post('/uploading', fd, config ).then(response => { this.$message.success(response.retCode) }) },
二、后台post
@ApiOperation("上传文件") @PostMapping(value = "/uploading") public @ResponseBody String uploadFile(@RequestParam("filename") MultipartFile file) { log.info("接收到的文件数据为:" + file); if (file.isEmpty()) { return "上传文件为空";
} // 获取文件全名a.py String fileName = file.getOriginalFilename(); // 文件上传路径
String templatePath = "E:/file/template/" log.info("文件路径:" + templatePath); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); //获取文件名 String prefixName = fileName.substring(0, fileName.lastIndexOf(".")); // 解决中文问题,liunx 下中文路径,图片显示问题 //fileName = UUID.randomUUID() + suffixName; File dest0 = new File(templatePath); File dest = new File(dest0, prefixName + File.separator + fileName); //文件上传-覆盖 try { // 检测是否存在目录 if (!dest0.getParentFile().exists()) { dest0.getParentFile().mkdirs(); //检测文件是否存在 } if (!dest.exists()) { dest.mkdirs(); } file.transferTo(dest); return "上传成功"; } catch (Exception e) { log.error("文件上传错误"); return "上传失败"; } }
三、效果演示jsonp