【问题标题】:Spring : File Upload RESTFUL Web ServiceSpring:文件上传 RESTFUL Web 服务
【发布时间】: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


【解决方案1】:

你可以像下面这样创建你的休息服务。

@RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload( 
            @RequestParam("file") MultipartFile file){
            String name = "test11";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = 
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

对于客户端,请执行以下操作。

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class Test {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:8080/upload");
    File file = new File("C:\\Users\\Kamal\\Desktop\\PDFServlet1.pdf");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "multipart/form-data");
    mpEntity.addPart("file", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}

【讨论】:

  • 我试过了,但再次遇到 500 错误代码。 java.lang.IllegalStateException: Current request is not of type [org.springframework.web.multipart.MultipartRequest]: org.apache.catalina.connector.RequestFacade@7de7432b 我已经用客户端代码更新了我的问题。我现在很困惑。 :(
  • 您在客户端使用什么?您能否也提供一些客户端代码,从您向此服务发出请求的位置?
  • 我已经更新了你可以找到客户端代码的问题。我正在使用 apache http 客户端。
  • 刚刚更新了之前的服务代码,还提供了客户端代码来测试,对我有用!!!
  • 我试过这段代码。不幸的是,它不适合我。收到此错误。 Required MultipartFile parameter 'file' is not present</u></p><p><b>description</b>The request sent by the client was syntactically incorrect.
【解决方案2】:

<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

需要此代码

【讨论】:

  • 感谢您的建议。但这根本不是问题。 MultipartResolver Bean 已经存在。请检查我已接受的答案。
  • 这个脚本的目的是什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 2012-07-24
  • 2017-01-20
  • 2011-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多