Java Spring:文件上传restfulweb服务

Java Spring:文件上传restfulweb服务,java,web-services,rest,spring-mvc,Java,Web Services,Rest,Spring Mvc,我正在使用Spring4.0为RESTfulWeb服务创建POC。 如果我们只传递字符串或任何其他基本数据类型,它就可以正常工作 @RequestMapping(value="/upload/file", method=RequestMapping.post) public String uploadFile(@RequestParam("fileName", required=false) String fileName){ logger.info("initialization of

我正在使用Spring4.0为RESTfulWeb服务创建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. "); 
  //------------
   }  
客户端代码-使用ApacheHttpClient

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();
    }

您可以像下面这样创建rest服务

@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();
  }
}
对于客户端,请执行以下操作

@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();
  }
}


从服务器的角度来看,它将接收一个
多部分文件
。从HTTP的角度来看,它将传输
多部分/表单数据
。从客户的角度来看。。。好的,这将取决于客户端库…嗯,在使用
多部分/表单数据时,您不应该使用
@RequestBody
注释,但您应该查看Spring参考手册,了解如何配置应用程序来处理文件上载。@serge:我已经尝试过了,但遇到了415个错误。请给我推荐好的参考链接。@SergeBallesta:
@RequestParam
我用过,但有500个错误。我想如果我与特定的html表单集成,它就会工作,然后它就会工作。否则它可能无法工作
@RequestParam(value=“path”)文件文件
我可能错了。您可以在Spring参考手册或StackOverflow中找到使用Spring上载文件的示例:()或()我尝试了此操作,但再次遇到500个错误代码<代码>java.lang.IllegalStateException:当前请求的类型不是[org.springframework.web.multipart.MultipartRequest]:org.apache.catalina.connector。RequestFacade@7de7432b
我已经用客户代码更新了我的问题。我现在很困惑(你在客户端使用的是什么?你能不能也提供一些客户端代码,从哪里向该服务发出请求?我已经更新了问题,你可以在那里找到客户端代码。我正在使用apache http客户端。刚刚更新了以前的服务代码,还提供了客户端代码进行测试,这对我有效!!!我尝试了此代码。unfoRTU对我不起作用。获取此错误。
所需的MultipartFile参数“file”不存在

说明客户端发送的请求在语法上不正确。
感谢您的建议。但这根本不是问题。MultipartResolver Bean已经存在。请检查我已接受的答案.这个剧本的目的是什么?