HttpPost 上传文件

/**
 * Project Name:testHttpClient
 * File Name:ClientMultipartFormPost.java
 * Package Name:com.test.httpclient
 * Date:2016年12月28日下午4:01:59
 * Copyright (c) 2016, [email protected] All Rights Reserved.
 *
 */

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.HttpMultipartMode;
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;  
/**
 * ClassName:ClientMultipartFormPost 
* Function: TODO ADD FUNCTION.
* Reason: TODO ADD REASON.
* Date: 2016年12月28日 下午4:01:59
* @author ZengZhuo(lenovo) * @version * @since JDK 1.8+ * @see */ public class ClientMultipartFormPost { /** * 这个例子展示了如何执行请求包含一个多部分编码的实体 * 模拟表单提交 * @throws IOException */ public static void main(String[] args) throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); try{ //要上传的文件的路径 String filePath = "D:\\mail.jpeg"; //把一个普通参数和文件上传给下面这个地址 是一个servlet HttpPost httpPost = new HttpPost("http://localhost:8080/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().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addPart("media", bin)//相当于 .addPart("comment", comment) .addPart("name", name)//相当于 .addPart("password", password) .addTextBody("value", "roy") .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(); } } }
package com.test.httpclient;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;  

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public UploadServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		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 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 iter = items.iterator();  
                while (iter.hasNext()) {  
                    FileItem item = iter.next();  
                    //如果是普通表单属性  
                    if (item.isFormField()) {  
                        //  
                        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);  
                    }  
                }  
            }  
        }
	}
	
	public static void main(String[] args) {
		String name ="aaa";
		String [] values = new String[]{"123"};
		Map ms = new HashMap();
		ms.put(name, values);
		System.out.println(ms.toString());
	}
}

  4.0.0
  Systemmonitor
  Systemmonitor
  0.0.1-SNAPSHOT
  war
  
  
  
    
      org.apache.openejb
      javaee-api
      5.0-1
      provided
    
    
      javax.faces
      jsf-api
      1.2_04
      provided
    
    
      javax.servlet
      jstl
      1.2
      provided
    
    
      javax.servlet.jsp
      jsp-api
      2.1
      provided
    
    
      javax.faces
      jsf-impl
      1.2_04
      provided
    
    
    	org.springframework
    	spring-web
    	3.1.1.RELEASE
    	jar
    	compile
    
    
    	org.springframework
    	spring-core
    	3.1.1.RELEASE
    	jar
    	compile
    
    
    	org.springframework
    	spring-webmvc
    	3.1.1.RELEASE
    	jar
    	compile
    
  
  
    ${basedir}/src
    ${basedir}/WebRoot/WEB-INF/classes
    
      
        ${basedir}/src
        
          **/*.java
        
      
    
    
      
        maven-war-plugin
        
          ${basedir}/WebRoot
          ${basedir}/WebRoot
        
      
      
        maven-compiler-plugin
        
          1.5
          1.5
        
      
    
  

 

你可能感兴趣的:(HttpPost 上传文件)