HttpURLConnection 多文件上传 和 参数

修改过的:
客户端:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class t {
	public static void main(String[] args) throws IOException {
		URL postUrl = new URL("http://localhost:8080/test_client/callback.action");
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);                
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        String content = "fileInfo="+URLEncoder.encode("file1", "utf-8")+"¶m="+URLEncoder.encode("pppp","utf-8");//多个参数中间用&连接
        out.writeBytes(content);
        out.flush();
        out.close(); // flush and close
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
                System.out.println(line);
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();
 }
}
 
 
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.lubansoft.test.upload.po.UploadRecord;

public class TestClient {

	public static void main(String[] args) {
		TestClient client = new TestClient();
		client.upload();
	}

	private void upload() {
		try {
			String boundary = "------WebKitFormBoundaryUey8ljRiiZqhZHBu";
			String url = "http://localhost:8080/upload/FileUpLoad";
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Charsert", "UTF-8");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			// 指定流的大小,当内容达到这个值的时候就把流输出
			conn.setChunkedStreamingMode(10240);
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes();// 定义最后数据分隔线
			List list  = new ArrayList();
			list.add("e:/userInfo.properties");
			list.add("e:/email.html");
			StringBuilder sb = new StringBuilder();
			//添加form属性
			sb.append("--");
			sb.append(boundary);
			sb.append("\r\n");
			sb.append("Content-Disposition: form-data; name=\"username\"");
			sb.append("\r\n\r\n");
			sb.append("hello word");
			out.write(sb.toString().getBytes("utf-8"));
			out.write("\r\n".getBytes("utf-8"));
			
			int leng = list.size();
			for (int i = 0; i < leng; i++) {
				String fname = list.get(i);
				File file = new File(fname);
				sb = new StringBuilder();
				sb.append("--");
				sb.append(boundary);
				sb.append("\r\n");
				sb.append("Content-Disposition: form-data;name=\"file" + i
						+ "\";filename=\"" + file.getName() + "\"\r\n");
				sb.append("Content-Type:application/octet-stream\r\n\r\n");
				byte[] data = sb.toString().getBytes();
				out.write(data);
				DataInputStream in = new DataInputStream(new FileInputStream(
						file));
				int bytes = 0;
				byte[] bufferOut = new byte[1024];
				while ((bytes = in.read(bufferOut)) != -1) {
					out.write(bufferOut, 0, bytes);
				}
				out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
				in.close();
			}
			out.write(end_data);
			out.flush();
			out.close();
			// 定义BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			System.out.println("发送POST请求出现异常!" + e);
			e.printStackTrace();
		}
	}

}
 服务器端:
package com.lubansoft.test.upload.web.servlet;

import java.io.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

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;

/**
 * 
 * @author Administrator
 * 文件上传
 * 具体步骤:
 * 1)获得磁盘文件条目工厂 DiskFileItemFactory 要导包
 * 2) 利用 request 获取 真实路径 ,供临时文件存储,和 最终文件存储 ,这两个存储位置可不同,也可相同
 * 3)对 DiskFileItemFactory 对象设置一些 属性
 * 4)高水平的API文件上传处理  ServletFileUpload upload = new ServletFileUpload(factory);
 * 目的是调用 parseRequest(request)方法  获得 FileItem 集合list ,
 *     
 * 5)在 FileItem 对象中 获取信息,   遍历, 判断 表单提交过来的信息 是否是 普通文本信息  另做处理
 * 6)
 *    第一种. 用第三方 提供的  item.write( new File(path,filename) );  直接写到磁盘上
 *    第二种. 手动处理  
 *
 */
public class FileUpLoad extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");	//设置编码
		
		//获得磁盘文件条目工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//获取文件需要上传到的路径
		HttpSession session = request.getSession();
		String path = session.getServletContext().getRealPath("/uploadFiles");
		
		//如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
		//设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
		/**
		 * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 
		 * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的 
		 * 然后再将其真正写到 对应目录的硬盘上
		 */
		factory.setRepository(new File(path));
		//设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
		factory.setSizeThreshold(1024*1024) ;
		
		//高水平的API文件上传处理
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		
		try {
			//可以上传多个文件
			List list = (List)upload.parseRequest(request);
			
			for(FileItem item : list)
			{
				//获取表单的属性名字
				String name = item.getFieldName();
				
				//如果获取的 表单信息是普通的 文本 信息
				if(item.isFormField())
				{					
					//获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
					String value = item.getString() ;
					
					request.setAttribute(name, value);
				}
				//对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
				else
				{
					/**
					 * 以下三步,主要获取 上传文件的名字
					 */
					//获取路径名
					String value = item.getName() ;
					if(value == null || value.equals("")){
						continue;
					}
					//索引到最后一个反斜杠
					int start = value.lastIndexOf("\\");
					//截取 上传文件的 字符串名字,加1是 去掉反斜杠,
					String filename = value.substring(start+1);
					
					request.setAttribute(name, filename);
					
					//真正写到磁盘上
					//它抛出的异常 用exception 捕捉
					
					//item.write( new File(path,filename) );//第三方提供的
					
					//手动写的
					OutputStream out = new FileOutputStream(new File(path,filename));
					
					InputStream in = item.getInputStream() ;
					
					int length = 0 ;
					byte [] buf = new byte[1024] ;
					
					System.out.println("获取上传文件的总共的容量:"+item.getSize());

					// in.read(buf) 每次读到的数据存放在   buf 数组中
					while( (length = in.read(buf) ) != -1)
					{
						//在   buf 数组中 取出数据 写到 (输出流)磁盘上
						out.write(buf, 0, length);
					    
					}
					
					in.close();
					out.close();
				}
			}
			
			
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
		}
		
		
		request.getRequestDispatcher("fileDemo.jsp").forward(request, response);
		

	}

}
 
 
 
Java利用HttpURLConnection发送post请求上传文件

 

Java中利用HttpURLConnection发送post和get请求

 

 

 

 Servlet实现文件上传,可多文件上传

你可能感兴趣的:(文件断点,上传)