Reputation: 5684
I'm having the follwing controller:
@RequestMapping(value = "/uploadCert", method = RequestMethod.POST)
@ResponseBody
public String uploadCert( @RequestParam(value = "file", required = false) List<MultipartFile> files){
for (MultipartFile file : files) {
String path = "tempFolder";
File targetFile = new File(path);
try {
FileUtils.copyInputStreamToFile(file.getInputStream(), targetFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return "done";
}
Tested by the following unit test:
@Test
public void uploadCertFile() throws Exception {
//given
MockMultipartFile file = new MockMultipartFile("file", "test.txt", "text/plain", "bar".getBytes());
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.fileUpload("/uploadCert").file(file);
System.out.println(request);
//when
ResultActions resultActions = mockMvc.perform(request);
//then
MvcResult mvcResult = resultActions.andReturn();
assertEquals(200, mvcResult.getResponse().getStatus());
File savedFile = new File("./test.txt");
assertTrue(savedFile.exists());
savedFile.delete();
}
which it workign good, i have another server in java code that would need to upload files into the above controller. I was trying to look for parallel of MockMVCRequestMapping to be use in the code but could not find it, what should i use insted to send this web request from a java code?
Upvotes: 2
Views: 1102
Reputation: 1550
You can do something like this:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<String> uploadDocument(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
Iterator<String> iterator = request.getFileNames();
MultipartFile multipartFile = null;
while (iterator.hasNext()) {
multipartFile = request.getFile(iterator.next());
final String fileName = multipartFile.getOriginalFilename();
final String fileSize = String.valueOf(multipartFile.getSize());
//do rest here
}
}
Upvotes: 1