`

文件上传的例子

    博客分类:
  • java
阅读更多
package seentao.vbse.devdocument.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

import nc.bs.framework.common.NCLocator;
import nc.uap.lfw.core.log.LfwLogger;
import nc.vo.pub.lang.UFDate;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import seentao.vbse.devdocument.inf.service.IStudentDevDocumentService;
import seentao.vbse.devdocument.vo.DevDocumentBVO;
import seentao.vbse.devdocument.vo.DevDocumentHVO;
import seentao.vbse.devdocument.vo.DevDocumentVO;
import seentao.vbse.util.imp.CommonResource;

public class Upload extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private String filePath = "C:/temp/"; // 文件存放目录
	private String tempPath = "C:/temp/buffer"; // 临时文件目录
	//主表信息
	private DevDocumentHVO devHVO = null;
	//教学计划Id
	private String instplanmgmtPK = "";
	//教学案例
	private String teachingcasePK = "";
	//学生编号
	private String usercode = "";
	
	//上传业务接口
	private IStudentDevDocumentService studentDevDocumentService = null;
	//学生上传文档路径
	private String fullPath = "";
	//保持成功之后主表主键
	private String devPK = "";
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}


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

		response.setContentType("text/html; charset=UTF-8");
		PrintWriter pw = response.getWriter();
		//创建文件上传路径
		String realPath = request.getSession().getServletContext().getRealPath("/");
		filePath = realPath + CommonResource.RESOURCES_UPLOAD_STUDENT_DOCUMENT_PATH;
		tempPath = filePath + "/buffer";
		if (!new File(filePath).isDirectory()){
			new File(filePath).mkdirs();
		}
		if (!new File(tempPath).isDirectory()){
			new File(tempPath).mkdirs();
		}
		
		try {
			DiskFileItemFactory diskFactory = new DiskFileItemFactory();
			// threshold 极限、临界值,即硬盘缓存 1M
			diskFactory.setSizeThreshold(4 * 1024);
			// repository 贮藏室,即临时文件目录
			diskFactory.setRepository(new File(tempPath));

			ServletFileUpload upload = new ServletFileUpload(diskFactory);
			// 设置允许上传的最大文件大小 300M
			upload.setSizeMax(300 * 1024 * 1024);
			// 解析HTTP请求消息头
			List<FileItem> fileItems = upload.parseRequest(request);
			Iterator<FileItem> iter = fileItems.iterator();
			//新建主表对象
			devHVO = new DevDocumentHVO();
			devHVO.setIsallupload("0");
			//子表数据
			List<DevDocumentBVO> devBVOArray = new ArrayList<DevDocumentBVO>();
			
			//处理表单内容
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					//处理表单内容 
					processFormField(item, pw);
				} else {
					//上传目录加教学计划加学生编号
					if(!instplanmgmtPK.isEmpty() && !teachingcasePK.isEmpty() && !usercode.isEmpty()){
						
						fullPath = (filePath + "/" + instplanmgmtPK + "/" + teachingcasePK + "/" +usercode);
						if(!new File(fullPath).isDirectory()){
							new File(fullPath).mkdirs();
						}

					}
					
					//处理上传的文件 
					processUploadFile(item, devBVOArray);
				}
			}
			
			//保持上传信息
			DevDocumentVO devVO = new DevDocumentVO(devHVO,devBVOArray);
			devPK = getStuDocumentService().saveStuDocument(devVO);
			
			if((devPK !=null) && (!devPK.isEmpty())){
				String url = "devedition/devdocument/uploaddocument/stu_success.jsp?devPK="+devPK;
				request.getRequestDispatcher(url).forward(request, response);
			}

			
		} catch (Exception e) {
			pw.println("学生开发文档提交失败!");
			System.out.println("使用 fileupload 包时发生异常 ...");
			LfwLogger.error("使用 fileupload 包时发生异常 ..."+e);
			//e.printStackTrace();
		}

	}

	// 处理表单内容
	private void processFormField(FileItem item, PrintWriter pw)
			throws Exception {
		String name = item.getFieldName();
		String value = item.getString("utf-8");
		
		if("instplanmgmtPK".equals(name)){
			instplanmgmtPK = value;
			devHVO.setTeachingplanid(value);
		}
		
		if("teachingcasePK".equals(name)){
			teachingcasePK = value;
			devHVO.setDevcaseid(value);
		}
		
		if("usercode".equals(name)){
			usercode = value;
			devHVO.setUsercode(value);
		}
		
		if("username".equals(name)){
			devHVO.setUsername(value);
		}
		
		if("userPK".equals(name)){
			devHVO.setUserid(value);
		}	
		//pw.println(name + " : " + value + "\r\n");
	}

	// 处理上传的文件
	private void processUploadFile(FileItem item, List<DevDocumentBVO> devBVOArray)
			throws Exception {
		
		String documenttype = "0";
		String fieldname = item.getFieldName();
		String fileUploadPath = "";
		if("uploadfile1".equals(fieldname)){
			//概要设计文档
			documenttype = "1";
			if(new File(fullPath+"/1").isDirectory()){
				//清空学生已经上传的文件
				delAllFile(fullPath+"/1");
			}else{
				new File(fullPath+"/1").mkdirs();
			}
			
			fileUploadPath = fullPath+"/1";
			
		}else if("uploadfile2".equals(fieldname)){
			//详细设计文档
			documenttype = "2";
			if(new File(fullPath+"/2").isDirectory()){
				//清空学生已经上传的文件
				delAllFile(fullPath+"/2");
			}else{
				new File(fullPath+"/2").mkdirs();
			}
			
			fileUploadPath = fullPath+"/2";
			
		}else if("uploadfile3".equals(fieldname)){
			//数据库说明文档
			documenttype = "3";
			if(new File(fullPath+"/3").isDirectory()){
				//清空学生已经上传的文件
				delAllFile(fullPath+"/3");
			}else{
				new File(fullPath+"/3").mkdirs();
			}
			
			fileUploadPath = fullPath+"/3";
			
		}else if("uploadfile4".equals(fieldname)){
			//程序
			documenttype = "4";
			if(new File(fullPath+"/4").isDirectory()){
				//清空学生已经上传的文件
				delAllFile(fullPath+"/4");
			}else{
				new File(fullPath+"/4").mkdirs();
			}
			
			fileUploadPath = fullPath+"/4";
		}

		// 文件名
		String filename = item.getName();
		// System.out.println("完整的文件名:" + filename);
		int index = filename.lastIndexOf("\\");

		filename = filename.substring(index + 1, filename.length());

		long fileSize = item.getSize();

		if ("".equals(filename) && fileSize == 0) {
			System.out.println("文件名为空 ...");
			return;
		}

		File uploadFile = new File(fileUploadPath + "/" + filename);
		item.write(uploadFile);
		
		//保存文件
		//DevDocumentHVO devHVO = new DevDocumentHVO();
		DevDocumentBVO devBVO = new DevDocumentBVO();
		devBVO.setDocumenttype(documenttype);
		devBVO.setFilename(filename);
		devBVO.setFilepath(uploadFile.getPath());
		devBVO.setUploaddate(new UFDate());
		
		devBVOArray.add(devBVO);
		//pw.println(filename + " 文件保存完毕 ...");
		//pw.println("文件大小为 :" + fileSize + "\r\n");
	}

	// 如果要在配置文件中读取指定的上传文件夹,可以在init()方法中执行:
	public void init() throws ServletException {

	}
	
	// 删除指定文件夹下所有文件
	// param path 文件夹完整绝对路径
	public boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		int j = 0;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
				j++;
			}
		}
		
		if(j == tempList.length){
			flag = true;
		}
		
		return flag;
	}
	
	public IStudentDevDocumentService getStuDocumentService(){
		if( studentDevDocumentService == null){
			studentDevDocumentService = NCLocator.getInstance().lookup(IStudentDevDocumentService.class);
		}

		return studentDevDocumentService;
		
		
	}
	
	
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics