0

I have a Java HttpClient that executes the following code:

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://exampleutl.com/upload/");

File file = new File("C:/src_path/binary.doc");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

builder.setMode(HttpMultipartMode.STRICT);

FileBody fileBody = new FileBody(file); //image should be a String
builder.addPart("file", fileBody);
post.setEntity(builder.build());

client.execute(post);

I cannot figure out what the server method mapped to the /upload/ path should look like.

The server that accepts this file upload request is Spring 4.0. Something like this:

@RequestMapping(method = RequestMethod.POST, value = "/upload/")
public @ResponseBody String saveUpload(UploadDto dto) throws IOException,ServletException {
    File file = new File("C:/dest_path/" + dto.getFile().getOriginalFilename());
    FileUtils.writeByteArrayToFile(file, dto.getFile().getBytes());
    return "success";
}

The above server method gets called by the client.execute() but the UploadDto is empty. Here is the UploadDto:

public class UploadDto {
    private MultipartFile file;

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }
}

Any assistance would be greatly appreciated!

4

2 回答 2

1

您似乎缺少MultipartResolverSpring servlet 上下文中的 bean。就像是

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    return multipartResolver;
}

您将请求发送至

HttpPost post = new HttpPost("http://exampleutl.com/upload/");

假设您的上下文路径是 ROOT,即。为空,您的处理程序方法应映射到/upload.

@RequestMapping(method = RequestMethod.POST, value = "/upload")
于 2014-04-24T22:36:40.790 回答
0

最终的答案是服务器方法应该如下所示:

@RequestMapping(method = RequestMethod.POST, value = "/upload/")
public @ResponseBody String saveUpload(@RequestParam("file") final MultipartFile mpf) throws IOException, ServletException, FileUploadException {
    File file = new File("C:/dest_path/" + mpf.getOriginalFilename());
    FileUtils.writeByteArrayToFile(file, mpf.getBytes());

    return "success";
}

正如 Sotirios Delimanois 所提到的,MultipartResolver 确实也是解决方案的必需部分:

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    return multipartResolver;
} 
于 2014-04-24T23:49:41.980 回答