HTTP利用MultipartEntityBuilder模拟表单上传文件

Java代码 

  1. /** 
  2.      * 模拟表单上传文件 
  3.      */  
  4.      public Map<String,Object> uploadFileByHTTP(File postFile,String postUrl,Map<String,String> postParam){  
  5.          Map<String,Object> resultMap = new HashMap<String,Object>();  
  6.          CloseableHttpClient httpClient = HttpClients.createDefault();    
  7.          try{    
  8.              //把一个普通参数和文件上传给下面这个地址    是一个servlet    
  9.              HttpPost httpPost = new HttpPost(postUrl);    
  10.              //把文件转换成流对象FileBody  
  11.              FileBody fundFileBin = new FileBody(postFile);    
  12.              //设置传输参数  
  13.              MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();    
  14.              multipartEntity.addPart(postFile.getName(), fundFileBin);//相当于<input type="file" name="media"/>    
  15.              //设计文件以外的参数  
  16.              Set<String> keySet = postParam.keySet();  
  17.              for (String key : keySet) {  
  18.                 //相当于<input type="text" name="name" value=name>    
  19.                 multipartEntity.addPart(key, new StringBody(postParam.get(key), ContentType.create("text/plain", Consts.UTF_8)));    
  20.              }  
  21.                
  22.              HttpEntity reqEntity =  multipartEntity.build();   
  23.              httpPost.setEntity(reqEntity);    
  24.                  
  25.              log.info("发起请求的页面地址 " + httpPost.getRequestLine());    
  26.              //发起请求   并返回请求的响应    
  27.              CloseableHttpResponse response = httpClient.execute(httpPost);    
  28.              try {    
  29.                  log.info("----------------------------------------");    
  30.                  //打印响应状态    
  31.                  log.info(response.getStatusLine());  
  32.                  resultMap.put("statusCode", response.getStatusLine().getStatusCode());  
  33.                  //获取响应对象    
  34.                  HttpEntity resEntity = response.getEntity();    
  35.                  if (resEntity != null) {    
  36.                      //打印响应长度    
  37.                      log.info("Response content length: " + resEntity.getContentLength());    
  38.                      //打印响应内容    
  39.                      resultMap.put("data", EntityUtils.toString(resEntity,Charset.forName("UTF-8")));  
  40.                  }    
  41.                  //销毁    
  42.                  EntityUtils.consume(resEntity);    
  43.              } catch (Exception e) {  
  44.                  e.printStackTrace();  
  45.              } finally {    
  46.                  response.close();    
  47.              }    
  48.          } catch (ClientProtocolException e1) {  
  49.             e1.printStackTrace();  
  50.          } catch (IOException e1) {  
  51.             e1.printStackTrace();  
  52.          } finally{    
  53.              try {  
  54.                 httpClient.close();  
  55.              } catch (IOException e) {  
  56.                 e.printStackTrace();  
  57.              }    
  58.          }  
  59.         log.info("uploadFileByHTTP result:"+resultMap);  
  60.         return resultMap;    
  61.      }  

 servlet接收代码:

Java代码  

  1. package com.pingan.web;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.util.Iterator;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.annotation.WebServlet;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.apache.commons.fileupload.FileItem;  
  15. import org.apache.commons.fileupload.FileUploadException;  
  16. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  17. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  18.   
  19. import com.alibaba.fastjson.JSONObject;  
  20.   
  21. /** 
  22.  * Servlet implementation class FileUploadServlet 
  23.  */  
  24. @WebServlet(description = "文件上传", urlPatterns = { "/FileUploadServlet" })  
  25. public class FileUploadServlet extends HttpServlet {  
  26.       
  27.     private static final long serialVersionUID = 1L;  
  28.    
  29.     /** 
  30.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  31.      */  
  32.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  33.         this.doPost(request, response);  
  34.     }  
  35.   
  36.     /** 
  37.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  38.      */  
  39.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  40.         request.setCharacterEncoding("utf-8");  
  41.         response.setCharacterEncoding("utf-8");  
  42.         //利用apache的common-upload上传组件来进行  来解析获取到的流文件  
  43.         //把上传来的文件放在这里  
  44.         String uploadPath = getServletContext().getRealPath("/upload");//获取文件路径   
  45.         //检测是不是存在上传文件  
  46.         // Check that we have a file upload request  
  47.         boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
  48.           
  49.         if(isMultipart){  
  50.               
  51.             DiskFileItemFactory factory = new DiskFileItemFactory();  
  52.             //指定在内存中缓存数据大小,单位为byte,这里设为1Mb  
  53.             factory.setSizeThreshold(1024*1024);  
  54.             //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录   
  55.             factory.setRepository(new File("D://temp"));  
  56.             // Create a new file upload handler  
  57.             ServletFileUpload upload = new ServletFileUpload(factory);  
  58.             // 指定单个上传文件的最大尺寸,单位:字节,这里设为5Mb    
  59.             upload.setFileSizeMax(5 * 1024 * 1024);    
  60.             //指定一次上传多个文件的总尺寸,单位:字节,这里设为10Mb    
  61.             upload.setSizeMax(10 * 1024 * 1024);     
  62.             upload.setHeaderEncoding("UTF-8"); //设置编码,因为我的jsp页面的编码是utf-8的   
  63.               
  64.             List<FileItem> items = null;  
  65.               
  66.             try {  
  67.                 // 解析request请求  
  68.                 items = upload.parseRequest(request);  
  69.             } catch (FileUploadException e) {  
  70.                 e.printStackTrace();  
  71.             }  
  72.             if(items!=null){  
  73.                 //把上传文件放到服务器的这个目录下  
  74.                 if (!new File(uploadPath).isDirectory()){    
  75.                     new File(uploadPath).mkdirs(); //选定上传的目录此处为当前目录,没有则创建    
  76.                 }   
  77.                 //解析表单项目  
  78.                 // Process the uploaded items  
  79.                 Iterator<FileItem> iter = items.iterator();  
  80.                 while (iter.hasNext()) {  
  81.                     FileItem item = iter.next();  
  82.                     //如果是普通表单属性  
  83.                     if (item.isFormField()) {  
  84.                         //<input type="text" name="content">  
  85.                         String name = item.getFieldName();//相当于input的name属性  
  86.                         String value = item.getString();//input的value属性  
  87.                         System.out.println("属性:"+name+" 属性值:"+value);  
  88.                     }  
  89.                     //如果是上传文件  
  90.                     else {  
  91.                         //属性名  
  92.                         String fieldName = item.getFieldName();  
  93.                         //上传文件路径  
  94.                         String fileName = item.getName();  
  95.                         fileName = fileName.substring(fileName.lastIndexOf("/")+1);// 获得上传文件的文件名  
  96.                         try {  
  97.                             item.write(new File(uploadPath,fileName));  
  98.                         } catch (Exception e) {  
  99.                             e.printStackTrace();  
  100.                         }  
  101.                         //给请求页面返回响应  
  102.                         JSONObject jsonObject = new JSONObject();  
  103.                         jsonObject.put("code", "0000");  
  104.                         jsonObject.put("msg", "文件上传成功! 文件名是:"+fileName);  
  105.                         response.getWriter().println(jsonObject.toJSONString());  
  106.                     }  
  107.                 }  
  108.             }  
  109.         }  
  110.     }  
  111. }  

 

测试main方法:

Java代码 

  1. public static void main(String[] args) {  
  2.         HttpsFileUtils httpsUtils = new HttpsFileUtils();  
  3.         //要上传的文件的路径    
  4.         String filePath = "D:/git/fastPlat/commonWeb/src/com/pingan/file/data/base64_New2.jpg";    
  5.         String postUrl  = "http://localhost:8080/commonWeb/FileUploadServlet";  
  6.         Map<String,String> postParam = new HashMap<String,String>();  
  7.         postParam.put("custNo", "11122");  
  8.         File postFile = new File(filePath);  
  9.         Map<String,Object> resultMap = httpsUtils.uploadFileByHTTP(postFile,postUrl,postParam);  
  10.         System.out.println(resultMap);  
  11.     }  

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Apache HttpClient和MultipartEntityBuilder来发送form-data格式的文件。下面是一个示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.HttpClientBuilder; import java.io.File; import java.io.IOException; public class FormDataExample { public static void main(String[] args) { // 创建HttpClient实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建HttpPost请求 HttpPost httpPost = new HttpPost("http://example.com/upload"); // 创建MultipartEntityBuilder MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文件参数 File file = new File("path/to/file"); builder.addBinaryBody("file", file); // 构建HttpEntity对象 HttpEntity entity = builder.build(); // 将HttpEntity对象设置到HttpPost请求中 httpPost.setEntity(entity); try { // 发送HttpPost请求并获取响应 HttpResponse response = httpClient.execute(httpPost); // 处理响应 // ... } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的示例中,你需要将`http://example.com/upload`替换为你要发送请求的URL。同时,将`path/to/file`替换为要上文件的路径。 这样,你就可以使用HttpClient和MultipartEntityBuilder来发送form-data格式的文件了。记得在使用HttpClient时,要注意关闭连接或使用连接池来管理连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值