chrome浏览器接收到上传文件地址
IE浏览器可以获取到真实路径
说是chrome出于安全考虑,搞了个虚拟路径fakepath
我的需求是:
表单上传文件和数据,封装到对象a里传给另一个服务去处理,
现在这个fakepath扔过去就是一个空文件对象,报错
解决:
一顿百度chrome咋拿file真实路径,
其实不用拿路径,拿到也没用,都不在一台服务器上,有路径也取不到文件,
上传的文件spring帮我们生成了一个临时文件
所以,直接从前台传文件对象
form.append("file", document.getElementById("file").files[0]);
后台拿到文件对象直接传给另一个服务就可以了
public Response saveLetterManage(@RequestParam(name = "file",required = false) MultipartFile file,@RequestParam("dataParam") String dataParams) {}
tip:
1、这里eureka传文件有问题,我做了下转化
public static File convert(MultipartFile file){File convFile = new File("tempFile", file.getOriginalFilename());if (!convFile.getParentFile().exists()) {System.out.println("mkdir:" + convFile.getParentFile().mkdirs());}try {convFile.createNewFile();FileOutputStream fos = new FileOutputStream(convFile);fos.write(file.getBytes());fos.close();} catch (IOException e) {e.printStackTrace();}return convFile;}
2、不能把file对象封装到表单对象里,文件字节流转json对象会失败,所以分开两个参数传,文件对象和表单数据json串
/*** 调用远程服务,传文件和表单数据* @param url 服务接口地址* @param vo 表单数据* @return* @throws IOException*/public String sendRequest(String url, AppntRelationVo vo) throws IOException {MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();if(vo.getFile() != null){bodyMap.add("file", new FileSystemResource(convert(vo.getFile())));vo.setFile(null);}JSONObject obj = (JSONObject) JSONObject.toJSON(vo);bodyMap.add("body", obj.toJSONString());HttpHeaders headers = new HttpHeaders();headers.setExpires(50000);headers.setContentType(MediaType.MULTIPART_FORM_DATA);HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyMap, headers);ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);return JSON.toJSONString(response);}
服务端正常接收就可以了
public Response saveStuff(@RequestParam(name = "file",required = false)MultipartFile file,@RequestParam("body")String formDataStr){}