Jsp 使用 fileupload 文件上传和下载

Jsp 使用 fileupload 文件上传和下载_第1张图片

前言

Jsp文件上传的目前主要有两个常用的:
1、SmartUpload
2、Apache Commons fileupload

我在期末的 Jsp 大作业需要一个文件上传下载模块,使用了第2个 Apache 的包,这里我主要写写文件上传和下载的普通用法、注意的问题、最重要的是 表单的文本和文件一块提交的写法。


文件上传

第一步、我们应该引入2个包:

commons-fileupload-1.2.1.jar
commons-io-1.4.jar

注:这两个 jar 包配合使用,都需要引入,文末会附上下载链接。此外,这应该不是最新版,有强迫症的同学可以去 apache 看看。


第二步、放上 index.jsp 的表单:

	//略过非重点...
	

我们可以看到:
form 的 method 是 post 的;
form 的内容格式要定义为 multipart/form-data 格式;
form 的 文件input 的 type 是 file;
对,这三条是必须的!当然这里表单还有stuid和workid。


第三步、UploadServlet 代码

@WebServlet("/UploadServlet") 
public class UploadServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	private String filePath; // 文件存放目录
	private String tempPath; // 临时文件目录
	private String studentid;
	private String workid;
	private String filename ;
	private String SQLFileName;

	// 初始化
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		// 可以从配置文件中获得初始化参数
		//filePath = config.getInitParameter("filepath");
		//tempPath = config.getInitParameter("temppath");
		//ServletContext context = getServletContext();
		//filePath = context.getRealPath(filePath);
		//tempPath = context.getRealPath(tempPath);
		filePath="D:/ClassHelpFile/file";
		tempPath="D:/ClassHelpFile/temp";
	}

	// doPost
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		//res.setContentType("text/plain;charset=gbk");
		PrintWriter pw = res.getWriter();
		try {
			DiskFileItemFactory diskFactory = new DiskFileItemFactory();
			// threshold 极限、临界值,即硬盘缓存 1M
			diskFactory.setSizeThreshold(10 * 1024);
			// repository 贮藏室,即临时文件目录
			diskFactory.setRepository(new File(tempPath));
			
			ServletFileUpload upload = new ServletFileUpload(diskFactory);
			//防止乱码
			upload.setHeaderEncoding("UTF-8");
			// 设置允许上传的最大文件大小 4M
			upload.setSizeMax(10 * 1024 * 1024);
			// 解析HTTP请求消息头
			List fileItems = upload.parseRequest(req);
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					processFormField(item, pw);//处理表单内容
				} else {
					processUploadFile(item, pw);//处理上传的文件
					
				}
			}
			
			SQLFileName=tempPath+"/"+filename;
			System.out.println(workid+" & "+studentid+" & "+SQLFileName);
			//保存到数据库
			String sql = "insert into finishwork(workid,studentid,fileurl) values('"+workid+"','"+studentid+"','"+SQLFileName+"')";
			Connection conn = DBbean.getConn();
			Statement stmt = DBbean.getStatement(conn);
			DBbean.getResultSetOfInsert(stmt, sql);
			DBbean.close(stmt);
			DBbean.close(conn);	
			
			pw.close();
			
		} catch (Exception e) {
			System.out.println("异常:使用 fileupload 包发生异常!");
			e.printStackTrace();
		}
		RequestDispatcher rd =req.getRequestDispatcher("/student/index_student.jsp?id="+studentid);
		try{
			rd.forward(req, res);
			return;
		}catch(Exception e){
			System.out.print(e.toString());
		}
		return;
	}

	// 处理表单内容
	private void processFormField(FileItem item, PrintWriter pw)
			throws Exception {
		String name = item.getFieldName();
		if(name.equals("stuid")){
			studentid = item.getString();
		}else if(name.equals("workid")){
			workid = item.getString();
		}
	}

	// 处理上传的文件
	private void processUploadFile(FileItem item, PrintWriter pw)
			throws Exception {
		filename = item.getName();
		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(filePath + "/" + filename);
		item.write(uploadFile);
		//pw.println(filename + " 文件保存完毕 !");
		//pw.println("文件大小为 :" + fileSize + "\r\n");
	}

	// doGet
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		//doPost(req, res);
	}
}

上述代码注释很详尽,其中,我们可以清楚的看到,处理表单普通内容的 processFormField 方法和处理上传的文件的 processUploadFile方法。特别注意 processFormField 方法,需要根据 form 表单的 name 来获取内容。
这样我们可以把表单的普通文本和文件一块提交啦!


文件下载

表单就不放了,直接来 DownloadServlet:

/**
 * 文件下载
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String path;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取传送的文件路径
		path = request.getParameter("fileurl");
		if (path != null) {
			download(response);
		}
	}

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

	public void download(HttpServletResponse response) throws IOException {
		//去掉路径,剩下文件名。
		String realPath = path.substring(path.lastIndexOf("/") + 1);
		// 告诉浏览器是以下载的方法获取到资源,以此种编码来解析。
		response.setHeader("content-disposition", "attachment; filename="
				+ URLEncoder.encode(realPath, "utf-8"));
		// 获取资源,保存。
		FileInputStream fis = new FileInputStream(path);
		int len = 0;
		byte[] buf = new byte[1024];
		while ((len = fis.read(buf)) != -1) {
			response.getOutputStream().write(buf, 0, len);
		}
		fis.close();
	}

}

这里传入了文件路径,获取文件进行保存。


下载jar包

点我下载


你可能感兴趣的:(Web)