文件上传服务器接收

package com;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.ArrayList;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tools.ant.taskdefs.Mkdir;

public class UploadServlet extends HttpServlet {

	private boolean isMultipart;
	private String filePath;
	private int maxFileSize = 1000 * 1024 * 1024;
	private int maxMemSize = 1000 * 1024 * 1024;
	private File file;

	public void init() {
		// Get the file location where it would be stored.
		filePath = getServletContext().getInitParameter("file-upload");
		File upLoadFileLocation = new File(filePath);
		if (!upLoadFileLocation.exists()) {
			upLoadFileLocation.mkdirs();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		// Check that we have a file upload request
		isMultipart = ServletFileUpload.isMultipartContent(request);
		response.setContentType("text/html");
		java.io.PrintWriter out = response.getWriter();
		if (!isMultipart) {
			out.println("");
			out.println("");
			out.println("Servlet upload");
			out.println("");
			out.println("");
			out.println("

No file uploaded

"); out.println(""); out.println(""); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); List files = new ArrayList(); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { files.add(fi); } } files.get(0); FileItem fi = files.get(0); // 获取文件名F://123.jpg (上传人的路径) String fileName = fi.getName(); // 得到后缀名 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1) .toLowerCase(); // 得到文件夹名称 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // 换个新名字 fileName = fileName.replace("."+fileExt, ""); String newFileName = fileName + sdf.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; // 上传路径 if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + newFileName); } else { file = new File(filePath + newFileName); } fi.write(file); if (fileExt.equalsIgnoreCase("zip")) { ZipTools ZipTools = new ZipTools(file.getPath()); File unCompressFile = new File(file.getParent() +"\\"+ fileName); if (!unCompressFile.exists()) { unCompressFile.mkdirs(); } ZipTools.unCompress(unCompressFile.getPath()); // 解压到指定目录 } out.println("Uploaded Filename: " + fileName + "
"); } catch (Exception ex) { System.out.println(ex); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { throw new ServletException("GET method used with " + getClass().getName() + ": POST method required."); } }

client


package com.nnn.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nnn.bean.FileBean;

/** 
 * @author NNN 
 * @date 2014年11月27日 上午11:27:58 
 */

public class UploadTools {

	protected final static Log log = LogFactory.getLog(UploadTools.class);

	private HttpServletRequest request = null;
	private String savePath = "";
	private List fileBeanList = null;
	// 上传表单的其它信息,除file类型的input
	private Map formDatas = null;
	private String uploadStatus = "";
	// 文件单个最大大小
	private long maxSize;
	// 文件允许的格式为
	private String allowExts;
	// 文件不允许的格式为
	private String unAllowExts;

	public void uploadFiles() {
		savePath = this.getSavePath();
		fileBeanList = new ArrayList();
		formDatas = new HashMap();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(this.getRequest());// 上传文件解析
			// 表单元素集合
			List formFieldList = new ArrayList();
			// 文件元素集合
			List fileFieldList = new ArrayList();
			if (items.size() > 0) {
				// 将表单元素和文件元素装载到不同的集合中
				for (FileItem fileItem : items) {
					if (fileItem.isFormField()) {
						formFieldList.add(fileItem);
					} else {
						fileFieldList.add(fileItem);
					}
				}

				/**
				 * 分解表单元素
				 */
				// 初始化文件上传属性bean
				FileBean fileBean = null;
				for (FileItem fileItem : formFieldList) {
					System.out.println("表单参数名:" + fileItem.getFieldName() + ",表单参数值:" + fileItem.getString("UTF-8"));
					formDatas.put(fileItem.getFieldName(), fileItem.getString("UTF-8").replace("'", "''"));
					if (fileItem.getFieldName().equals("articleUUID")) {
						savePath = savePath.replace("uuid", fileItem.getString("UTF-8"));
					}
				}
				log.info("保存的真实路径为:" + savePath);

				/**
				 * 分解文件元素
				 */
				for (FileItem fileItem : fileFieldList) {
					// 先判断文件件域是否选择了文件
					if (fileItem.getName() != null && !fileItem.getName().equals("")) {
						// 文件名
						String fileName = fileItem.getName();
						// IE 和 FireFox 下的 getName() 得出的值不同
						// IE 下得到的是文件的完整路径
						if (fileName.contains("\\")) {
							// 截取得到完整路径后的文件名
							fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
						}
						// 文件大小
						long fileSize = fileItem.getSize();
						// 检查扩展名
						String extName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
						// 文件属性bean
						fileBean = new FileBean();
						fileBean.setFileName(fileName);
						fileBean.setExtName(extName);
						fileBean.setFileSize(fileSize);
						SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
						// 转换文件名字
						String newFileName = fileName + "_" + df.format(new Date());

						fileBean.setFilePath(savePath + newFileName);
						fileBean.setFieldName(fileItem.getFieldName());
						fileBean.setNewFileName(newFileName);
						File f1 = new File(savePath);
						if (!f1.exists()) {
							f1.mkdirs();
						}
						System.out.println("新文件路径:" + newFileName);
						File uploadedFile = new File(savePath, newFileName);
						fileItem.write(uploadedFile);
						// 获取根目录对应的真实物理路径
						// 保存文件在服务器的物理磁盘中
						System.out.println("上传文件的大小:" + fileItem.getSize());
						System.out.println("上传文件的类型:" + fileItem.getContentType());
						System.out.println("上传文件的名称:" + fileName);
						fileBeanList.add(fileBean);
						uploadStatus = "上传成功";
					} else {
						uploadStatus = "没有选择文件!";
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			uploadStatus = "上传文件失败!";
		}
	}

	public List getFileBeanList() {
		return fileBeanList;
	}

	public void setFileBeanList(List fileBeanList) {
		this.fileBeanList = fileBeanList;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public Map getFormDatas() {
		return formDatas;
	}

	public void setFormDatas(Map formDatas) {
		this.formDatas = formDatas;
	}

	public String getUploadStatus() {
		return uploadStatus;
	}

	public void setUploadStatus(String uploadStatus) {
		this.uploadStatus = uploadStatus;
	}

	public long getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(long maxSize) {
		this.maxSize = maxSize;
	}

	public String getAllowExts() {
		return allowExts;
	}

	public void setAllowExts(String allowExts) {
		this.allowExts = allowExts;
	}

	public String getUnAllowExts() {
		return unAllowExts;
	}

	public void setUnAllowExts(String unAllowExts) {
		this.unAllowExts = unAllowExts;
	}

	public void uploadFile(File file, String url) {
		if (!file.exists()) {
			return;
		}
		PostMethod postMethod = new PostMethod(url);
		try {
			// FilePart:用来上传文件的类
			FilePart fp = new FilePart("filedata", file);
			Part[] parts = { fp };

			// 对于MIME类型的请求,httpclient建议全用MulitPartRequestEntity进行包装
			MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());
			postMethod.setRequestEntity(mre);
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 设置连接时间
			int status = client.executeMethod(postMethod);
			if (status == HttpStatus.SC_OK) {
				System.out.println(postMethod.getResponseBodyAsString());
			} else {
				System.out.println("fail");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 释放连接
			postMethod.releaseConnection();
		}
	}

}


压缩zip包


package com.nnn.util;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Expand;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;

/** 
 * @author NNN 
 * @date 2014年12月3日 下午1:43:49 
 */

public class ZipTools {
	private File zipFile;    
    
    public ZipTools(String pathName) {    
        this.zipFile = new File(pathName);    
    }    
        
    public boolean compress(String srcPathName) {    
        return compress(srcPathName, "", "");  
    }     
      
    public boolean compress(String srcPathName, String includes, String excludes) {    
        File srcdir = new File(srcPathName);    
        if (!srcdir.exists()){    
            System.out.println(srcPathName + "不存在!");  
            return false;    
        }    
        Project prj = new Project();    
        Zip zip = new Zip();    
        zip.setProject(prj);    
        zip.setDestFile(zipFile);    
        FileSet fileSet = new FileSet();    
        fileSet.setProject(prj);    
        fileSet.setDir(srcdir);    
        fileSet.setIncludes(includes); //包括哪些文件或文件夹 eg:zip.setIncludes("*.java");    
        fileSet.setExcludes(excludes); //排除哪些文件或文件夹    
        zip.addFileset(fileSet);              
        zip.execute();   
        return true;  
    }     
      
    public boolean unCompress(){  
        return unCompress(this.zipFile.getParent());  
    }  
  
    public boolean unCompress(String dest){  
        Expand expand = new Expand();  
        expand.setOverwrite(true);  
        expand.setSrc(this.zipFile);  
        expand.setDest(new File(dest));  
        expand.execute();  
        return true;      
    }  
      
/*    public static void main(String[] args){  
        ZipTools ZipTools1 = new ZipTools("D:/z1.zip");  
        ZipTools1.compress("D:/com");    //把D:/com下的所有文件和子目录中的文件一起打包;不包括D:/com本身  
          
        ZipTools ZipTools2 = new ZipTools("D:/z2.zip");  
        ZipTools2.compress("D:/com",   //根目录  
                        "testcase/*.java",   //includes, 支持通配符匹配,多个子项时以逗号或空格分隔  
                        "");   //excludes, 支持通配符匹配,多个子项时以逗号或空格分隔  
          
        ZipTools ZipTools3 = new ZipTools("D:/z3.zip");  
        ZipTools3.compress("D:/com",   
                        "",   //includes, 支持通配符匹配,多个子项时以逗号或空格分隔  
                        "testcase/testfile.xml");   //excludes, 支持通配符匹配,多个子项时以逗号或空格分隔  
          
        ZipTools ZipTools4 = new ZipTools("D:/z3.zip");  
        ZipTools4.unCompress();    //解压到当前目录  
        ZipTools4.unCompress("E:/");     //解压到指定目录       
    }  */   
}



server


package com;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.ArrayList;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tools.ant.taskdefs.Mkdir;

public class UploadServlet extends HttpServlet {

	private boolean isMultipart;
	private String filePath;
	private int maxFileSize = 1000 * 1024 * 1024;
	private int maxMemSize = 1000 * 1024 * 1024;
	private File file;

	public void init() {
		// Get the file location where it would be stored.
		filePath = getServletContext().getInitParameter("file-upload");
		File upLoadFileLocation = new File(filePath);
		if (!upLoadFileLocation.exists()) {
			upLoadFileLocation.mkdirs();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, java.io.IOException {
		// Check that we have a file upload request
		isMultipart = ServletFileUpload.isMultipartContent(request);
		response.setContentType("text/html");
		java.io.PrintWriter out = response.getWriter();
		if (!isMultipart) {
			out.println("");
			out.println("");
			out.println("Servlet upload");
			out.println("");
			out.println("");
			out.println("

No file uploaded

"); out.println(""); out.println(""); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); List files = new ArrayList(); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { files.add(fi); } } files.get(0); FileItem fi = files.get(0); // 获取文件名F://123.jpg (上传人的路径) String fileName = fi.getName(); // 得到后缀名 String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1) .toLowerCase(); // 得到文件夹名称 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String ymd = sdf.format(new Date()); sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // 换个新名字 fileName = fileName.replace("."+fileExt, ""); String newFileName = fileName + sdf.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt; // 上传路径 if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + newFileName); } else { file = new File(filePath + newFileName); } fi.write(file); if (fileExt.equalsIgnoreCase("zip")) { ZipTools ZipTools = new ZipTools(file.getPath()); File unCompressFile = new File(file.getParent() +"\\"+ fileName); if (!unCompressFile.exists()) { unCompressFile.mkdirs(); } ZipTools.unCompress(unCompressFile.getPath()); // 解压到指定目录 } out.println("Uploaded Filename: " + fileName + "
"); } catch (Exception ex) { System.out.println(ex); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { throw new ServletException("GET method used with " + getClass().getName() + ": POST method required."); } }

server listener


package com;


import org.apache.commons.fileupload.ProgressListener;

public class FileUploadProgressListener implements ProgressListener {

	public FileUploadProgressListener() {
		super();
		// TODO Auto-generated constructor stub
		System.out.println("Progress Listened!");
	}

	@Override
	public void update(long pBytesRead, long pContentLength, int pItems) {
		// TODO Auto-generated method stub

		System.out.println("现在已经处理了" + pBytesRead
				+ "数据,总数据量" + pContentLength
				+ "正在处理" + pItems);

	}

}



你可能感兴趣的:(文件上传服务器接收)