vue代码(使用element-ui):
思路:依次遍历fileList数组,将其中的每个图片文件提取出,再加入到formdata中,因为是多文件上传,后端以文件数组的形式接受,
因此每次合并到formdata的key值都为同一值。
uploadImg() { let imgfile = new FormData(); for (var i = 0; i < this.fileList.length; i++) { // files[i] = this.fileList[i].raw; imgfile.append("files",this.fileList[i].raw); } // console.log("文件长度",files.length); imgfile.append("id",this.radio); console.log("将要上传的文件:",imgfile.get("files")); if (this.fileList.length > 0) { this.$ajax({ method: "post", url: "/xxxx/xxxx/xxxxxxxx/productImg", data: imgfile }).then(resp => { console.log("返回值:",resp.data.code) if (resp.data.code) { this.$message({ message: "上传药材图片成功", type: "success" }); } else { this.$message({ message: "上传药材图片失败", type: "warning" }) } this.cleanImg(); this.dialogUploadPhoto = false; }) } else { this.$message({ message: "请选择需要上传的图片", type: "warning" }); } }
后端代码:
Controller:
@PostMapping("productImg") public ResponseEntity<Map<String,Object>> uploadImg(@RequestParam("files")MultipartFile[] files, HttpServletRequest request, @RequestParam Map<String, Object> map) { return ResponseEntity.status(HttpStatus.CREATED).body(productBaseService.saveImg(files,request,map)); }
service:
@Override public Map<String, Object> saveImg(MultipartFile[] files, HttpServletRequest request, Map<String, Object> map) { Map<String,Object> maps = new HashMap<String, Object>();try { // 判断文件数组是否为空 if (files == null || files.length < 1) { maps.put("code",false); } else { System.out.println("有数据"); //判断是否有路径 String path = Constant.IMG_PATH_FILE; if (!new File(path).exists()) { new File(path).mkdirs(); } // 遍历图片文件 for (int i = 0; i < files.length; i++) { MultipartFile file = files[i]; // 将图片文件保存到服务器,同时返回上传后图片的名字 String image = uploadFile(file,path,map); ProductBaseImg productBaseImg = new ProductBaseImg(); productBaseImg.setId(UUIDUtil.uuid()); productBaseImg.settImgId(image); productBaseImg.settProductbaseId((String)map.get("id")); productBaseImgMapper.insert(productBaseImg); System.out.println("上传成功"); } maps.put("code",true); } } catch (IOException e) { maps.put("code",false); e.printStackTrace(); } return maps; } public static String uploadFile(MultipartFile file,String path,Map<String, Object> map) throws IOException { String name = file.getOriginalFilename(); String suffixName = name.substring(name.lastIndexOf(".")); // 生成图片id String imgid = UUIDUtil.uuid(); String fileName = imgid + suffixName; File tempFile = new File(path,fileName); if(!tempFile.getParentFile().exists()){ tempFile.getParentFile().mkdir(); } if(tempFile.exists()){ tempFile.delete(); } tempFile.createNewFile(); file.transferTo(tempFile); return tempFile.getName(); }
原文地址:https://www.cnblogs.com/flypig666/p/12267718.html
时间: 2024-11-05 14:46:15