简体   繁体   中英

How to upload file to a spring mvc RestController using post method

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?

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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM