jsp+servlet+commons-fileupload-1.3.jar+commons-io-2.4.jar+jstl标签库实现文件上传与下载

  下面按照从用户访问请求开始,到得到结果的处理流程(从用户上传界面到用户下载处理的整个过程代码).粘贴的代码

1.视图界面upload.jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@include file="/common/tag.jsp"%>
<%@include file="/common/jquery.jsp"%>






My JSP 'index.jsp' starting page






	
	




	
${requestScope.msg}

2.视图upload中使用的tag.jsp和jquery.jsp代码如下

tag.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

jquery.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>






My JSP 'jquery.jsp' starting page



















依赖的国际化资源文件内容:csdn_zh.properties

uploadUser=\u4E0A\u4F20\u8005
submitUpload=\u4E0A\u4F20
uploadfile=\u4E0A\u4F20\u6587\u4EF6



jsp+servlet+commons-fileupload-1.3.jar+commons-io-2.4.jar+jstl标签库实现文件上传与下载_第1张图片
3.上传文件 -servlet处理类

package upload.servlet;

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

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

/**
 * 
 * @author chenhongjun
 *
 */
public class UploadServlet extends HttpServlet {

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

		// 判断是否是上传表单是否为multipart/form-data类型
		if (ServletFileUpload.isMultipartContent(request)) {

			// 创建 DiskFileItemFactory工厂 对象
			DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
			// 创建DiskFileItemFactory的解析器对象
			ServletFileUpload fileUpload = new ServletFileUpload(
					diskFileItemFactory);

			// 设置上传头的编码格式
			fileUpload.setHeaderEncoding("UTF-8");
			// 设置文件上传大小的限制 为1M
			fileUpload.setFileSizeMax(1024 * 1024);
			// 注册监听 已经上传的进度
			fileUpload.setProgressListener(new ProgressListener() {
				@Override
				public void update(long pBytesRead, long pContentLength,
						int pItems) {

					System.out.println("到现在为止,  " + pBytesRead + " 字节已上传,总大小为 "
							+ pContentLength);

				}
			});

			try {
				// 解析request请求
				List fileItems = fileUpload.parseRequest(request);
				// fileItem 对应
				// fileItem 
				// 遍历操作
				for (FileItem fileItem : fileItems) {
					// 首先判断 是否是 普通的文本
					if (fileItem.isFormField()) {
						// 获取字段name值
						String name = fileItem.getFieldName();
						// 字段name值 相对应的value
						String value = fileItem.getString();
					} else {
						// 获取上传文件的名称 文件名称可能是(c:\xxxx\xxx\xx.jpg(IE浏览器) 或者
						// xx.jpg(火狐浏览器));
						String fileName = fileItem.getName();
						// 如果在IE浏览器中 ---> 先解析出xx.jpg
						int index = fileName.lastIndexOf("\\");
						// 进行判断是否 含有\
						if (index != -1) {
							// 含有\ 就解析出xx.jpg
							fileName = fileName.substring(index + 1);
						}
						// 添加时间戳 保证上传的文件名称唯一
						fileName = System.currentTimeMillis() + "_" + fileName;
						// 设置保存的路径 防止外部直接访问 存放在WEB-INF目录下
						String path = request.getServletContext().getRealPath(
								"/WEB-INF/upload");
						// 创建保存的文件
						File file = new File(path, fileName);
						// 获取请求的输入流对象
						InputStream is = fileItem.getInputStream();
						// 输出流对象
						FileOutputStream fos = new FileOutputStream(file);
						// 缓冲区大小
						byte[] buffer = new byte[1024];
						// 读取的长度
						int len = 0;
						// 读取 如果读取的结果为-1 证明读取完毕,否则继续读取
						while ((len = is.read(buffer)) != -1) {
							// 写入文件
							fos.write(buffer, 0, len);
						}
						// 关闭流的操作
						fos.close();
						is.close();

						// 删除临时文件
						fileItem.delete();

					}
				}
				// 转发到 显示所有上传文件的servlet处理
				request.getRequestDispatcher("/listFile.do").forward(request,
						response);

			} catch (FileUploadException e) {
				// 获取错误的异常信息
				String message = e.getMessage();
				// The field upload exceeds its maximum permitted size of
				// 1048576 bytes.
				// 如果存在 限制文件大小的字符 就提示 文件上传过大
				if (message.contains("permitted size of")) {
					request.setAttribute("msg", "文件上传过大");
				}
				// 转发到 文件上传界面
				request.getRequestDispatcher("./upload.jsp").forward(request,
						response);
			}

		}
	}

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

}

4.显示有上传文件的servlet处理类

package down.servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

/**
 * 
 * @author chenhongjun
 *
 */

public class ListFileServlet extends HttpServlet {

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

		// 遍历WEB-INF/upload下面的所有文件 并保存到map集合中
		// 获取下载的路径
		String path = request.getServletContext().getRealPath("/WEB-INF/upload");
		// 获取下载路径的文件对象
		File file = new File(path);
		//声明用来存储上传文件的 map对象
		Map map = new HashMap();
		//通过遍历 把文件存储到map中
		listFiles(file, map); 
		//存储到request域中
		request.setAttribute("map", map);
		//转发到显示的界面
		request.getRequestDispatcher("./listfile.jsp").forward(request,
				response);
	}

	//遍历文件操作
	private void listFiles(File file, Map map) {
		//获取当前文件下面的所有文件
		File files[] = file.listFiles();
		//遍历
		for (File f : files) {
			//判断是否是 文件
			if (f.isFile()) {
				//获取文件名称
				String fileName = f.getName();
				//获取_字符所在的索引位置
				int index = fileName.indexOf("_");
				//判断是否存在 
				if (index != -1) {
					//存在 就把文件存储到map中
					map.put(fileName, fileName.substring(index + 1));
				} else {
					//如果不存在,就暂时不处理
				}
			} else {
				//如果是文件夹,再进行遍历
				listFiles(f, map);
			}
		}
	}

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

}

5.显示所有上传文件 listfile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@include file="/common/tag.jsp"%>
<%@include file="/common/jquery.jsp"%>






My JSP 'index.jsp' starting page






	




    
    
     
        
        
          ${m.key}
            
         
        ${m.value}
下载我


jsp+servlet+commons-fileupload-1.3.jar+commons-io-2.4.jar+jstl标签库实现文件上传与下载_第2张图片

6.下载处理的servlet类

package down.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

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

public class DownFileServlet extends HttpServlet {

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

		// 文件下载
		// 获取下载的文件名称
		String fileName = request.getParameter("fileName");
		// 找到下载文件的具体路径
		String filePath = request.getServletContext().getRealPath(
				"/WEB-INF/upload/" + fileName);
		// 根据路径创建文件
		File file = new File(filePath);

		// 创建输入流对象
		FileInputStream fis = new FileInputStream(file);
		
		// 设置下载的类型 告诉浏览器 需要以下载的方式操作
		response.setContentType("application/x-msdownload");
		// 下载头设置
		response.setHeader("content-disposition", "attachment;fileName="
				+ java.net.URLEncoder.encode(fileName, "UTF-8"));

		// 写出的流
		OutputStream os = response.getOutputStream();

		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = fis.read(buffer)) != -1) {
			os.write(buffer, 0, len);
		}
		os.close();
		fis.close();

	}

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

}

    jsp+servlet+commons-fileupload-1.3.jar+commons-io-2.4.jar+jstl标签库实现文件上传与下载_第3张图片

jsp+servlet+commons-fileupload-1.3.jar+commons-io-2.4.jar+jstl标签库实现文件上传与下载_第4张图片

你可能感兴趣的:(JavaWeb课程总结系列)