2

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?

1 Answer 1

1

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
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.