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(); }
