我使用的是Spring 4的最新版本,我通常没有问题编写RESTful控制器。有一个传统的Web应用程序,它使用java.net.HTTPUrlConnection来执行多部分上传。我们上传的数据有3条: 1是PDF文件,我们有字节,那么另外两条数据只是2个字符串字段。Spring MVC文件上传与多部分数据和单元测试
首先让我告诉你春天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的发送数据的自定义对象,这是非常标准的代码。我现在确实信任它。
因此,根据我们如何发送数据,是否需要更改控制器来做任何不同的事情,还是看起来不错?
现在,这里是代码,我使用单元测试该控制器:
@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
我正在调查。如果我需要对如何创建我的测试进行任何更改,我对此非常开放。最终,我会让所有的东西在发送代码,接收控制器和单元测试之间同步。
提前致谢!像往常一样,如果有任何其他数据或信息,我可以提供,请让我知道。谢谢!