如何使用post方法将文件上传到spring mvc RestController

时间:2015-12-08 16:40:52

标签: java spring spring-mvc post spring-restcontroller

我有以下控制器:

Open Browser   url  phantomjs  desired_capabilities=javascriptEnabled:False

通过以下单元测试进行测试:

@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";
    }

它工作得很好,我在java代码中有另一台服务器,需要将文件上传到上面的控制器。我试图寻找并行MockMVCRequestMapping在代码中使用但无法找到它,我应该使用insted从java代码发送此Web请求?

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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