httpclient上传文件例子

JAVA代码:

 

package destoon;
import java.io.File;  
import java.io.IOException;  
  
import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.HttpStatus;  
import org.apache.http.client.ClientProtocolException;  
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.FileBody;  
import org.apache.http.entity.mime.content.StringBody;  
import org.apache.http.impl.client.DefaultHttpClient;  
import org.apache.http.util.EntityUtils;  

/**
 * 上传文件例子
 * @author YULI
 *
 */
public class HttpClientPostMethod {  
      
    public static void main(String[] args) throws ClientProtocolException, IOException {  
        post();  
    }  
  
    public static void post() throws ClientProtocolException, IOException {  
        HttpClient httpclient = new DefaultHttpClient();  
        HttpPost post = new HttpPost("http://localhost:8080/HttpUtils/action.jsp");  
        FileBody fileBody = new FileBody(new File("D:/临时文件/1.jpg"));  
        StringBody stringBody = new StringBody("文件的描述");  
        MultipartEntity entity = new MultipartEntity();  
        entity.addPart("file", fileBody);  
        entity.addPart("desc", stringBody);  
        post.setEntity(entity);  
        HttpResponse response = httpclient.execute(post);  
        if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){                  
            HttpEntity entitys = response.getEntity();  
            if (entity != null) {  
                System.out.println(entity.getContentLength());  
                System.out.println(EntityUtils.toString(entitys));  
            }  
        }  
        httpclient.getConnectionManager().shutdown();  
    }  
}  

 

JSP文件:

<%@page import="java.util.Iterator"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.List"%>
<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>upload.jsp</title>  
</head>  
<body>  
<%  
	String dir = application.getRealPath("/") + "temp\\";
    if (ServletFileUpload.isMultipartContent(request)) {  
        DiskFileItemFactory factory = new DiskFileItemFactory();  
        //设定内存可以存放文件的最大容量,单位字节,超过的部分会以临时文件的形式存放在硬盘上,这里设置成10兆  
        factory.setSizeThreshold(10485760);  
        File temp = new File("/temp/");    
       if(!temp.exists()){    
          temp.mkdirs();    
        }  
        //设置临时文件存放的位置  
       factory.setRepository(temp);  
          
       ServletFileUpload upload = new ServletFileUpload(factory);  
        //设置单个文件最大容量限制,-1表示没有限制    
        upload.setFileSizeMax(-1);  
        //设置整个请求的上传容量限制,-1表示没有限制    
        upload.setSizeMax(-1);  
          
        List<FileItem> items = upload.parseRequest(request);    
        Iterator<FileItem> iterator = items.iterator();  
        FileItem upload_item = null;  
        String desc = "";  
        while (iterator.hasNext()) {  
            FileItem item = iterator.next();  
            if(item.isFormField()){  
                //普通字段  
                //out.print(item.getFieldName());//得到字段name属性的值   
                //out.print(item.getString("UTF-8"));//得到字段的值  
                desc = item.getString("UTF-8");  
            }else{  
                //文件字段  
                //out.print("--------------");  
                //out.print(item.getFieldName());  
                //out.println(item.getContentType());//文件类型《application/pdf》  
                //out.println(item.getName());//文件名称《入门.pdf》                    
                //upload_item = item;
                item.write(new File(dir + "\\" + item.getName()));
            }  
        }  
    }  
%>  

 

你可能感兴趣的:(java)