前端上传多文件,携带多参数,java接收(省去频繁写一一对应的参数)

前端上传多文件,并携带多参数,为了方便后台接收,个人理解为:

	var data = new FormData();
	var dataMap = {
    
    };
	dataMap.name = name;
	dataMap.age = age;
	dataMap.sex = sex;
	dataMap.phone = phone;
	data.append("param",JSON.stringify(dataMap));

将前端的众多参数装进map中,然后将map转为json字符串。

后台接收–:

//上传基本资料
	@RequestMapping(value = "/uploadYhFile", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadYhFile(@RequestParam("profile") MultipartFile []profile,String param) throws IllegalStateException, IOException {
    
    
		//参数:param 要和前端FormData中的key对应
		HashMap hashMap = JSON.parseObject(param, HashMap.class); //將字符串转为map对象
		System.err.println(hashMap.get("name"));
		
		//文件循环接收插入---
		for (MultipartFile mFile : profile) {
    
    
			  String profilesPath = "D:\\photo";
				File file = new File(profilesPath);
				if (!file.exists()) {
    
    
					file.mkdirs();
				}

	        String FileName= mFile.getOriginalFilename();//获取文件名称
	        byte[] bytes = mFile.getBytes();//获取字节数组
	        String filePath= profilesPath+ File.separator+ FileName;
	        FileOutputStream fos= new FileOutputStream(new File(filePath)); //写出到文件
	        fos.write(bytes);
	        fos.flush();
	        fos.close();
		}
		
	
		return ret;
	}

猜你喜欢

转载自blog.csdn.net/bpdwg888/article/details/121554450