文件上传

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

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;

@WebServlet("/servlet/uploadServlet")
public class FileUpload extends HttpServlet {
     
	 private static String storeDirectory = null;
	
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		String  storeFile = "/uploadfiles";
		
	    storeDirectory = getServletContext().getRealPath(storeFile);
		System.out.println(storeDirectory);
		File file = new File(storeDirectory);
		if(!file.exists()){
			file.mkdir();
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		boolean b = ServletFileUpload.isMultipartContent(request);
		if(!b) {
			throw new RuntimeException("不是一個文件上传处理!");
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//设置缓存大小(Kb)
		factory.setSizeThreshold(20);
		List<FileItem> items =null;
		//获取ServletFileUpload对象
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		try {
			//将请求载入
			 items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		for (FileItem item : items) {
			//如果是普通的类型字段
			if(item.isFormField()) {
				System.out.println(item.getFieldName()+"---"+item.getContentType());
			//其他情况则代表上传	
			}else{
				//自定义函数处理上传文件
				 processUploadedFile(item);
			}
		}
		
	}

	private void processUploadedFile(FileItem item) {
		 String filename = item.getName();
		 File file = new File(storeDirectory+"/"+filename);
		
		 try {
			item.write(file);
		} catch (Exception e) {
			throw new RuntimeException("文件寫入失敗"+e);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


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