HttpClient4上传文件

这里用apache的HttpClient4.3模拟文件上传,上传到一个java servlet,然后用servlet解析,把上传文件放到服务器目录下


下面这个java应用,往一个java servlet中提交了一个文件,和几个普通表单属性

package com.test.httpClient;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


public class ClientMultipartFormPost {

	/**
	 * 这个例子展示了如何执行请求包含一个多部分编码的实体
	 * 模拟表单提交
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		try{
			//要上传的文件的路径
			String filePath = "D:\\my_shutdown.log";
			//把一个普通参数和文件上传给下面这个地址    是一个servlet
			HttpPost httpPost = new HttpPost("http://localhost:80/testjs/servlet/UploadServlet");
			//把文件转换成流对象FileBody
			FileBody bin = new FileBody(new File(filePath));
			//普通字段  重新设置了编码方式
			StringBody comment = new StringBody("这里是一个评论", ContentType.create("text/plain", Consts.UTF_8));
			//StringBody comment = new StringBody("这里是一个评论", ContentType.TEXT_PLAIN);
			
			StringBody name = new StringBody("王五", ContentType.create("text/plain", Consts.UTF_8));
			StringBody password = new StringBody("123456", ContentType.create("text/plain", Consts.UTF_8));
			
            HttpEntity reqEntity = MultipartEntityBuilder.create()
            .addPart("media", bin)//相当于<input type="file" name="media"/>
            .addPart("comment", comment)
            .addPart("name", name)//相当于<input type="text" name="name" value=name>
            .addPart("password", password)
            .build();
            
            httpPost.setEntity(reqEntity);
            
            System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
            //发起请求   并返回请求的响应
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                System.out.println("----------------------------------------");
                //打印响应状态
                System.out.println(response.getStatusLine());
                //获取响应对象
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                	//打印响应长度
                    System.out.println("Response content length: " + resEntity.getContentLength());
                    //打印响应内容
                    System.out.println(EntityUtils.toString(resEntity,Charset.forName("UTF-8")));
                }
                //销毁
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
		}finally{
			httpClient.close();
		}
	}

}

用于接收的java servlet  用到了apache的common-fileupload来解析请求main中提交的参数

<pre code_snippet_id="85986" snippet_file_name="blog_20131128_2_5126533" name="code" class="java">package com.vincente.test.servlet;  
  
  
import java.io.BufferedReader;  
import java.io.DataInputStream;  
import java.io.DataOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.io.PrintWriter;  
import java.net.HttpURLConnection;  
import java.net.URL;  
import java.util.Iterator;  
import java.util.List;  
  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
  
import org.apache.commons.fileupload.FileItem;  
import org.apache.commons.fileupload.FileItemFactory;  
import org.apache.commons.fileupload.FileUploadException;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  
  
public class UploadServlet extends HttpServlet {  
  
  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
  
    }  
  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        request.setCharacterEncoding("utf-8");  
        response.setCharacterEncoding("utf-8");  
          
        //利用apache的common-upload上传组件来进行  来解析获取到的流文件  
          
        //把上传来的文件放在这里  
        String uploadPath = getServletContext().getRealPath("/upload");//获取文件路径   
          
        //检测是不是存在上传文件  
        // Check that we have a file upload request  
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
          
        if(isMultipart){  
              
            DiskFileItemFactory factory = new DiskFileItemFactory();  
            //指定在内存中缓存数据大小,单位为byte,这里设为1Mb  
            factory.setSizeThreshold(1024*1024);  
            //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录   
            factory.setRepository(new File("D://temp"));  
            // Create a new file upload handler  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            // 指定单个上传文件的最大尺寸,单位:字节,这里设为5Mb    
            upload.setFileSizeMax(5 * 1024 * 1024);    
            //指定一次上传多个文件的总尺寸,单位:字节,这里设为10Mb    
            upload.setSizeMax(10 * 1024 * 1024);     
            upload.setHeaderEncoding("UTF-8"); //设置编码,因为我的jsp页面的编码是utf-8的   
              
            List<FileItem> items = null;  
              
            try {  
                // 解析request请求  
                items = upload.parseRequest(request);  
            } catch (FileUploadException e) {  
                e.printStackTrace();  
            }  
            if(items!=null){  
                //把上传文件放到服务器的这个目录下  
                if (!new File(uploadPath).isDirectory()){    
                    new File(uploadPath).mkdirs(); //选定上传的目录此处为当前目录,没有则创建    
                }   
                //解析表单项目  
                // Process the uploaded items  
                Iterator<FileItem> iter = items.iterator();  
                while (iter.hasNext()) {  
                    FileItem item = iter.next();  
                    //如果是普通表单属性  
                    if (item.isFormField()) {  
                        //<input type="text" name="content">  
                        String name = item.getFieldName();//相当于input的name属性  
                        String value = item.getString();//input的value属性  
                        System.out.println("属性:"+name+" 属性值:"+value);  
                    }  
                    //如果是上传文件  
                    else {  
                        //属性名  
                        String fieldName = item.getFieldName();  
                        //上传文件路径  
                        String fileName = item.getName();  
                        fileName = fileName.substring(fileName.lastIndexOf("/")+1);// 获得上传文件的文件名  
                        try {  
                            item.write(new File(uploadPath,fileName));  
                        } catch (Exception e) {  
                            e.printStackTrace();  
                        }  
                        //给请求页面返回响应  
                        response.getWriter().println("文件上传成功! 文件名是:"+fileName);  
                    }  
                }  
            }  
        }  
          
    <span style="font-family: Arial, Helvetica, sans-serif;">   }</span>  
</pre><pre code_snippet_id="85986" snippet_file_name="blog_20131128_2_5126533" name="code" class="java"><span style="font-family: Arial, Helvetica, sans-serif;"></span><pre code_snippet_id="85986" snippet_file_name="blog_20131128_2_5126533" name="code" class="plain">main中的执行结果:  
发起请求的页面地址 POST http://localhost:80/testjs/servlet/UploadServlet HTTP/1.1  
----------------------------------------  
HTTP/1.1 200 OK  
Response content length: 50  
文件上传成功! 文件名是:my_shutdown.log  
  
  
tomcat中的执行结果:  
属性:comment 属性值:这里是一个评论  
属性:name 属性值:王五  
属性:password 属性值:123456</pre><br>  
<br>  
<pre></pre>  
<p></p>  
<pre></pre>  
  
</pre>


转载于:https://my.oschina.net/cshuangxi/blog/270580

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值