vue ----element-ui 文件上传upload 组件 实现 及其后台
1、前台
action 不用改 :https://jsonplaceholder.typicode.com/posts/
getFile: 获取文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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) }) },
2、后台
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | @ApiOperation( "上传文件" ) @PostMapping(value = "/uploading" ) public @ResponseBody String uploadFile(@RequestParam( "filename" ) MultipartFile file) { log.info( "接收到的文件数据为:" + file); if (file.isEmpty()) { return "上传文件为空" ;<br> } // 获取文件全名a.py String fileName = file.getOriginalFilename(); // 文件上传路径<br> 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 "上传失败" ; } } |
3、效果演示
请保持微笑的眼睛,才能看到更多美丽的风景
余生很贵,请勿浪费
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步