【发布时间】:2014-11-11 03:27:14
【问题描述】:
我正在使用 Spring 4.0 为 RESTFUL Web 服务创建 POC。 如果我们只传递字符串或任何其他基本数据类型,它工作正常。
@RequestMapping(value="/upload/file", method=RequestMapping.post)
public String uploadFile(@RequestParam("fileName", required=false) String fileName){
logger.info("initialization of object");
//----------------------------------------
System.out.Println("name of File : " + fileName);
//----------------------------------------
}
这很好用。 但是如果我想将字节流或文件对象传递给函数,我该如何编写具有这些参数的函数?以及如何编写具有传递字节流的客户端?
@RequestMapping(value="/upload/file", method=RequestMapping.post)
public String uploadFile(@RequestParam("file", required=false) byte [] fileName){
//---------------------
//
}
我尝试了这段代码,但得到 415 错误。
@RequestMapping(value = "/upload/file", method = RequestMethod.POST, consumes="multipart/form-data")
public @ResponseBody String uploadFileContentFromBytes(@RequestBody MultipartFormDataInput input, Model model) {
logger.info("Get Content. ");
//------------
}
客户端代码 - 使用 apache HttpClient
private static void executeClient() {
HttpClient client = new DefaultHttpClient();
HttpPost postReqeust = new HttpPost(SERVER_URI + "/file");
try{
// Set Various Attributes
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("fileType" , new StringBody("DOCX"));
FileBody fileBody = new FileBody(new File("D:\\demo.docx"), "application/octect-stream");
// prepare payload
multipartEntity.addPart("attachment", fileBody);
//Set to request body
postReqeust.setEntity(multipartEntity);
HttpResponse response = client.execute(postReqeust) ;
//Verify response if any
if (response != null)
{
System.out.println(response.getStatusLine().getStatusCode());
}
}
catch(Exception ex){
ex.printStackTrace();
}
【问题讨论】:
-
从服务器的角度来看,它会收到一个
MultipartFile。从 HTTP 的角度来看,它将传输multipart/form-data。从客户端的角度来看......好吧,这将取决于客户端库...... -
恕我直言,在使用
multipart/form-data时不应使用@RequestBody注释,但您应该查看 Spring 参考手册以了解如何配置应用程序来处理文件上传。 -
@serge :我已经尝试过了,但遇到了 415 错误。请给我推荐好的参考链接。
-
@SergeBallesta:
@RequestParam我用过,我收到 500 错误。我想如果我与特定的 html 表单集成它会起作用,那么它会起作用。否则可能无法正常工作。@RequestParam(value="path") File file我可能错了。 -
您可以在 Spring 参考手册或 StackOverflow 中找到使用 Spring 上传文件的示例:(stackoverflow.com/questions/25286860/…) 或 (http://stackoverflow.com/questions/25460779/…)
标签: java web-services rest spring-mvc