原文: https://howtodoinjava.com/resteasy/jax-rs-resteasy-file-upload-httpclient-example/

    在以前的文章中,我们了解了文件下载以及构建 RESTful 客户端的知识。 现在,让我们继续前进。 在这篇文章中,我将提供使用 jax-rs resteasy 上传文件的示例代码。 要上传文件,将使用httpclient库代替 HTML 表单。

    我正在使用MultipartFormDataInput类,它是resteasy-multipart插件的一部分。

    1)更新项目的 Maven 依赖项

    在 maven 依赖项下添加/更新,以添加对项目中多部分文件上传的支持。

    1. <!-- core library -->
    2. <dependency>
    3. <groupId>org.jboss.resteasy</groupId>
    4. <artifactId>resteasy-jaxrs</artifactId>
    5. <version>2.3.1.GA</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>net.sf.scannotation</groupId>
    9. <artifactId>scannotation</artifactId>
    10. <version>1.0.2</version>
    11. </dependency>
    12. <!-- JAXB provider -->
    13. <dependency>
    14. <groupId>org.jboss.resteasy</groupId>
    15. <artifactId>resteasy-jaxb-provider</artifactId>
    16. <version>2.3.1.GA</version>
    17. </dependency>
    18. <!-- Multipart support -->
    19. <dependency>
    20. <groupId>org.jboss.resteasy</groupId>
    21. <artifactId>resteasy-multipart-provider</artifactId>
    22. <version>2.3.1.GA</version>
    23. </dependency>
    24. <!-- For better I/O control -->
    25. <dependency>
    26. <groupId>commons-io</groupId>
    27. <artifactId>commons-io</artifactId>
    28. <version>2.0.1</version>
    29. </dependency>

    还要添加下图给出的 jar 文件。 需要使用它们来构建用于文件上传示例的客户端代码。

    RESTEasy 文件上传 - `HttpClient`示例 - 图1

    HTTP 客户端 jar 文件

    2)准备将要在客户端上载文件的 http 客户端

    1. package com.howtodoinjava.client.upload;
    2. import java.io.File;
    3. import org.apache.http.HttpResponse;
    4. import org.apache.http.client.HttpClient;
    5. import org.apache.http.client.methods.HttpPost;
    6. import org.apache.http.entity.mime.MultipartEntity;
    7. import org.apache.http.entity.mime.content.FileBody;
    8. import org.apache.http.entity.mime.content.StringBody;
    9. import org.apache.http.impl.client.DefaultHttpClient;
    10. public class DemoFileUploader
    11. {
    12. public static void main(String args[]) throws Exception
    13. {
    14. DemoFileUploader fileUpload = new DemoFileUploader () ;
    15. File file = new File("C:/Lokesh/Setup/workspace/RESTfulDemoApplication/target/classes/Tulips.jpg") ;
    16. //Upload the file
    17. fileUpload.executeMultiPartRequest("http://localhost:8080/RESTfulDemoApplication/user-management/image-upload",
    18. file, file.getName(), "File Uploaded :: Tulips.jpg") ;
    19. }
    20. public void executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) throws Exception
    21. {
    22. HttpClient client = new DefaultHttpClient() ;
    23. HttpPost postRequest = new HttpPost (urlString) ;
    24. try
    25. {
    26. //Set various attributes
    27. MultipartEntity multiPartEntity = new MultipartEntity () ;
    28. multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
    29. multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;
    30. FileBody fileBody = new FileBody(file, "application/octect-stream") ;
    31. //Prepare payload
    32. multiPartEntity.addPart("attachment", fileBody) ;
    33. //Set to request body
    34. postRequest.setEntity(multiPartEntity) ;
    35. //Send request
    36. HttpResponse response = client.execute(postRequest) ;
    37. //Verify response if any
    38. if (response != null)
    39. {
    40. System.out.println(response.getStatusLine().getStatusCode());
    41. }
    42. }
    43. catch (Exception ex)
    44. {
    45. ex.printStackTrace() ;
    46. }
    47. }
    48. }

    3)在应用中编写 RESTful API 以接受多部分请求

    1. package com.howtodoinjava.client.upload;
    2. import java.io.File;
    3. import java.io.FileOutputStream;
    4. import java.io.IOException;
    5. import java.io.InputStream;
    6. import java.util.List;
    7. import java.util.Map;
    8. import javax.ws.rs.Consumes;
    9. import javax.ws.rs.POST;
    10. import javax.ws.rs.Path;
    11. import javax.ws.rs.core.MultivaluedMap;
    12. import javax.ws.rs.core.Response;
    13. import org.apache.commons.io.IOUtils;
    14. import org.jboss.resteasy.plugins.providers.multipart.InputPart;
    15. import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
    16. @Path("/user-management")
    17. public class DemoFileSaver_MultipartFormDataInput
    18. {
    19. private final String UPLOADED_FILE_PATH = "c:\temp\";
    20. @POST
    21. @Path("/image-upload")
    22. @Consumes("multipart/form-data")
    23. public Response uploadFile(MultipartFormDataInput input) throws IOException
    24. {
    25. //Get API input data
    26. Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
    27. //Get file name
    28. String fileName = uploadForm.get("fileName").get(0).getBodyAsString();
    29. //Get file data to save
    30. List<InputPart> inputParts = uploadForm.get("attachment");
    31. for (InputPart inputPart : inputParts)
    32. {
    33. try
    34. {
    35. //Use this header for extra processing if required
    36. @SuppressWarnings("unused")
    37. MultivaluedMap<String, String> header = inputPart.getHeaders();
    38. // convert the uploaded file to inputstream
    39. InputStream inputStream = inputPart.getBody(InputStream.class, null);
    40. byte[] bytes = IOUtils.toByteArray(inputStream);
    41. // constructs upload file path
    42. fileName = UPLOADED_FILE_PATH + fileName;
    43. writeFile(bytes, fileName);
    44. System.out.println("Success !!!!!");
    45. }
    46. catch (Exception e)
    47. {
    48. e.printStackTrace();
    49. }
    50. }
    51. return Response.status(200)
    52. .entity("Uploaded file name : "+ fileName).build();
    53. }
    54. //Utility method
    55. private void writeFile(byte[] content, String filename) throws IOException
    56. {
    57. File file = new File(filename);
    58. if (!file.exists()) {
    59. file.createNewFile();
    60. }
    61. FileOutputStream fop = new FileOutputStream(file);
    62. fop.write(content);
    63. fop.flush();
    64. fop.close();
    65. }
    66. }
    1. [源码下载](https://docs.google.com/file/d/0B7yo2HclmjI4amhXRE5VMjBRSHM/edit?usp=sharing "multipart rest file upload")

    祝您学习愉快!