上传文件2.0--drp203

上传文件2.0--drp203_第1张图片

package com.bjpowernode.drp.basedata.web;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

public class FileUploadServlet extends HttpServlet {

	/**
	 * Destruction of the servlet. <br>
	 */
	private String uploadPath = "D:\\addnetFile\\"; // 用于存放上传文件的目录
	private File tempPath = new File("D:\\addnetFile\\tmp\\"); // 用于存放临时文件的目录

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(4096);
		// the location for saving data that is larger than getSizeThreshold()
		factory.setRepository(tempPath);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum size before a FileUploadException will be thrown
		upload.setSizeMax(1000000 * 20);
		try {
			//循环获取所有的需要上传的文件细心
			List fileItems = upload.parseRequest(req);
			// assume we know there are two files. The first file is a small
			// text file, the second is unknown and is written to a file on
			// the server

		for(Iterator iter = fileItems.iterator();iter.hasNext();){
				FileItem item = (FileItem) iter.next();
				//上传域是否为input="type"输入域
				if (!item.isFormField()) {
					String fileName = item.getName();
					long size = item.getSize();
					if ((fileName == null || fileName.equals("")) && size == 0){
						continue;
					}

					//截取字符串,如:C:\Users\wm\Desktop\飞信截图20160213095859
					fileName=fileName.substring(fileName.lastIndexOf("\\")+1, fileName.length());
					item.write(new File(uploadPath  + fileName));

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 保存上传的文件到指定的目录

		// 在下文中上传文件至数据库时,将对这里改写

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occure
	 */
	public void init() throws ServletException {
		// Put your code here
	}
}

 

你可能感兴趣的:(上传文件2.0--drp203)