我有一个Java HttpClient,它执行以下代码:
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);
我不知道映射到/upload/path的服务器方法应该是什么样子。
接受此文件上传请求的服务器是Spring 4.0。类似这样的东西:
@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";
}
上面的服务器方法由client.execute()调用,但UploadDto为空。这是UploadDto:
public class UploadDto {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
如有任何协助,我们将不胜感激!
Spring servlet上下文中似乎缺少一个MultipartResolver
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")
最终的答案是服务器方法应该是这样的:
@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 Delimanis所提到的,MultipartResolver确实也是解决方案的必要组成部分:
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}