我最近使用Spring 4,编写RESTful控制器通常没问题。有一个遗留的Web应用程序,它使用java.net.HTTPUrlConnection进行多部分上传。我们上传了3条数据: 1是PDF文件,我们有字节,然后其他两个数据只是2个字符串字段。
首先让我向您展示Spring REST控制器以接受数据:
@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json", consumes = "multipart/form-data")
public @ResponseBody boolean saveData(@RequestPart(value = "field1") String field1, @RequestPart(value = "field2") String field2, @RequestParam(value = "pdfbytes") String pdfbytes)
{
System.out.println("saveData: field1=" + field1);
System.out.println("saveData: field2=" + field2);
System.out.println("saveData: pdfbytes=" + pdfbytes);
boolean response = true;
return response;
}
前端的代码,用于使用' java.net.HttpURLConnection'发送数据。 看起来像这样:
String boundary = MultiPartFormOutputStream.createBoundary();
URL uploadDocumentUrl = new URL(protocol + "://" + host + UPLOAD_EDITED_DOCUMENT);
HttpURLConnection urlConn = (HttpURLConnection) MultiPartFormOutputStream.createConnection(uploadDocumentUrl);
urlConn.setRequestProperty("Content-Type", MultiPartFormOutputStream.getContentType(boundary));
urlConn.setRequestProperty("Connection", "Keep-Alive");
urlConn.setRequestProperty("Cache-Control", "no-cache");
urlConn.setRequestProperty("User-Agent", userAgent);
urlConn.setRequestMethod("POST");
MultiPartFormOutputStream out = new MultiPartFormOutputStream(urlConn.getOutputStream(), boundary);
String pdfbytes= getEncodedDocument(pdf);
out.writeField("field1", field1);
out.writeField("field2", field2);
out.writeField("pdfbytes", pdfbytes);
out.close();
int responseCode = urlConn.getResponseCode();
String responseMessage = urlConn.getResponseMessage();
" MultiPartFormOutputStream"是一个自定义对象,它是为通过HttpUrlConnection发送数据而创建的,它是非常标准的代码。我现在确实相信它。
那么,根据我们发送数据的方式,我是否需要更改Controller以执行任何不同的操作,或者看起来不错?
现在这里是代码,我用于单元测试控制器:
@Test
public void testMockUpload() throws Exception
{
// Load resource being uploaded
byte[] pdfbytes = getByteArrayFromFile(FILENAME);
MockMultipartFile firstFile = new MockMultipartFile("field1", "", "text/plain", "field1 data".getBytes());
MockMultipartFile secondFile = new MockMultipartFile("field2", "", "text/plain", "field2 data".getBytes());
MockMultipartFile jsonFile = new MockMultipartFile("pdfbytes", "", "text/plain", pdfbytes);
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.fileUpload(BASE_URL + "/save").file(firstFile).file(secondFile).file(jsonFile)
.with(user(USERNAME).roles("role1", "role2")).contentType(MediaType.MULTIPART_FORM_DATA_VALUE);
this.mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk());
}
我现在得到的错误是: org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException
我正在调查。如果我需要对如何创建测试进行任何更改,我对此非常开放。最终,我将在发送代码,接收控制器和单元测试之间进行同步。
提前致谢!像往常一样,如果有任何其他数据或信息,我可以提供,请告诉我。谢谢!
答案 0 :(得分:0)
要上传一个文件,您可以将RequestParam类型定义为org.springframework.web.multipart.MultipartFile;
@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json", consumes = "multipart/form-data")
public @ResponseBody boolean saveData(@RequestParam(value = "file") MultipartFile file)
{
return response;
}
对于多个文件,我尝试创建一个Wrapper表单:
public class UploadForm{
private List<MultipartFile> files;
}
在控制器中绑定到此:
@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json", consumes = "multipart/form-data")
public @ResponseBody boolean saveData(@ModelAttribute uploadForm)
{
return response;
}
然后使用Spring对索引字段的支持来绑定到集合:
测试:
MockMultipartFile firstFile = new MockMultipartFile("files[0]", "", "text/plain", "field1 data".getBytes());
MockMultipartFile secondFile = new MockMultipartFile("files[1]", "", "text/plain", "field2 data".getBytes());
MockMultipartFile jsonFile = new MockMultipartFile("files[2]", "", "text/plain", pdfbytes);
客户端:
out.writeField("files[0]", file1Bytes);
out.writeField("files[1]", file2Bytes);
...