0
我想公開REST服務的文件上傳和編寫REST客戶端調用服務。我使用apache fileupload來使用文件,因爲我當前的應用程序是舊的,並且屬於2.5的servlet api時代。當我調用ServletFileUpload的parseRequest方法時,它不會從請求中返回任何文件並拋出Error對象。該應用程序還支持Spring 4apache fileupload parserequest不返回文件列表
REST客戶端
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("file", new ByteArrayResource(file.getBytes()));
parts.add("path", "C:/Temp/link.txt");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setContentDispositionFormData("filename","link.txt");
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(parts, headers);
ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:9080/contextroot/restservice.htm",requestEntity, String.class);
Servlet的REST服務
@RequestMapping(value = "restservice.htm")
public ResponseMessage restservice(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException, FileUploadException {
if(ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fileList = upload.parseRequest(request);
System.out.println("Headers : ");
Enumeration<String> headerEnumeration = request.getHeaderNames();
while(headerEnumeration.hasMoreElements()) {
String headerName = headerEnumeration.nextElement();
System.out.println("Name : " + headerName + ", Value : " + request.getHeader(headerName));
}
System.out.println("Parameters : ");
Enumeration<String> paramEnumeration = request.getParameterNames();
while(paramEnumeration.hasMoreElements()) {
String paramName = paramEnumeration.nextElement();
System.out.println("Name : " + paramName + ", Value : " + request.getParameter(paramName));
}
if(null == fileList || fileList.isEmpty()) {
//Setting ERROR
}
else {
//Setting SUCCESS
}
}
else {
//Setting ERROR
}
return message;
}
和輸出的頭是
Name : Accept, Value : text/plain, application/json, application/*+json, */*
Name : Content-Type, Value : multipart/form- data;boundary=CqVx3AfV3oq7XjEPmPkWXqve9lNs3Ntjhz1kBaI
Name : Content-Disposition, Value : form-data; name="filename"; filename="link.txt"
請求參數同時包含路徑和文件引用。
通常你會發布錯誤消息。當你說「拋出錯誤對象」時,很難幫助你。 – DavidS