JavaWeb实现文件上传与下载

1. 加强HttpServletResponse对象

    1. 实现一个加强的HttpServletResponse类,须要继承javax.servlet.http.HttpServletRequestWrapper类,经过重写本身须要加强的方法来实现(这种模式就叫作装饰者模式),使用该加强类在加上过滤器就能够实现无编码转换处理代码。javascript

public class MyRequest extends HttpServletRequestWrapper{
	private HttpServletRequest req;
	public MyRequest(HttpServletRequest request) {
		super(request);
		req=request;
	}
	@Override
	public String getParameter(String name) {
		//解决编码问题,不管是post仍是get请求,都不须要在业务代码中对编码再处理
		String method=req.getMethod();
		if("get".equalsIgnoreCase(method)){
			try {
				String str=req.getParameter(name);
				byte[] b=str.getBytes("iso8859-1");
				String newStr=new String(b, "utf-8");
				return newStr;
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if("post".equalsIgnoreCase(method)){
			try {
				req.setCharacterEncoding("utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//绝对不能删除此行代码,由于此行代码返回的就是编码以后的数据
		return super.getParameter(name);
	}

}

在过滤器中应用html

public class FilterTest4 implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//生成加强的HttpServletRequest对象
		HttpServletRequest req=(HttpServletRequest) request;
		MyRequest myReq=new MyRequest(req);
		//将加强的HttpServletRequest对象传入过滤器执行链中,在后面传入的request对象都会是加强的HttpServletRequest对象
		chain.doFilter(myReq, response);
		
	}

	@Override
	public void destroy() {}

}

2. 文件上传原理过程

    1. JavaWeb中实现文件上传:java

  • 客户端:HTML页面须要一个<form>表单,且必须设置表单的enctype属性值为"multipart/form-data",以及method属性值为"post"(由于get方式不支持大量数据提交);表单里有一个<input type="file" name="">的标签,且name属性值必须指定。
<html>
  <head>
    <title>My JSP 'upload.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
    <form action="" method="post" enctype="multipart/form-data">
        <input type="text" name="name">
    	请选择文件:<input type="file" name="upload">
    	<input type="submit" value="上传">
    </form>
  </body>
</html>
  • 服务端:主要进行IO读写操做。必须导入commons-fileupload和commons-io两个jar包,能够经过请求request对象的getInputStream得到一个流来读取请求中的文件数据,可是若是客户端上传多个文件时,就会很麻烦,因此提供了commons-fileupload和commons-io两个jar包来更方便的实现文件上传。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		/**
		 * 1. 建立磁盘文件项工厂类 DiskFileItemFactory
		 * 2. 建立核心解析Request类  ServletFileUpload
		 * 3. 开始解析Request对象中的数据,并返回一个List集合
		 * 4. List中包含表单中提交的内容
		 * 5. 遍历集合,获取内容
		 */
		DiskFileItemFactory fac=new DiskFileItemFactory();
		
		ServletFileUpload upload=new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");//防止中文的文件名乱码
		try {
			List<FileItem> fileItems = upload.parseRequest(req);
			for(FileItem item:fileItems){
				//有多是普通文本项,好比<input type="text">标签提交上来的字符串
				//也有多是<input type="submit" value="上传">上传的文件
				//文件项与普通项有不一样的API来处理
				//首先判断是普通文本项仍是文件项,
				if(item.isFormField()){
					//true表示普通文本项
					//获取文本项的name属性值
					String name=item.getFieldName();
					//获取对应的文本
					String value=item.getString("utf-8");//防止中文乱码
					System.out.println(name+":"+value);
				}else{
					//false表示文件项
					//先获取文件名称
					String name=item.getName();
					//获取文件项的输入流
					InputStream in=item.getInputStream();
					//获取服务器端文件存储的目标磁盘路径
					String path=getServletContext().getRealPath("/upload");
					System.out.println(path);
					//获取输出流,输出到本地文件中
					OutputStream out=new FileOutputStream(path+"/"+name);
					//写入数据
					int len=0;
					byte[] b=new byte[1024];
					while((len=in.read(b))!=-1){
						out.write(b,0,len);
					}
					in.close();
					out.close();
					
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

注意:在文件上传时,会将form表单的属性enctype属性值为"multipart/form-data",当提交到服务端后,没法使用 req.getParameter(name) 方法来获取到内容,只有经过上面的方法来获取文本项。算法

    2. 文件上传相关核心类:apache

  • DiskFileItemFactory:相关API以下
    • public DiskFileItemFactory():无参构造器
    • public DiskFileItemFactory(int sizeThreshold, File repository):构造器,sizeThreshold设置缓冲区大小,默认10240 byte;repository表示若是过缓冲区空间小于上传文件空间,那么会生成临时文件,repository就是指定该临时文件的保存路径,若是过未上传完成就中断,继续上传时就能够经过这个临时文件来继续上传。
    • public void setSizeThreshold(int sizeThreshold):设置缓冲区大小
    • public void setRepository(File repository):指定该临时文件的保存路径
//改进上面的文件上传代码,添加一个临时文件
public class UploadServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		DiskFileItemFactory fac=new DiskFileItemFactory();
		fac.setSizeThreshold(1024*1024);//设置缓冲区为1mb
		//设置临时文件的本地磁盘存储路径
		File repository=new File(getServletContext().getRealPath("/temp"));
		fac.setRepository(repository);
		ServletFileUpload upload=new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");//防止中文的文件名乱码
		try {
			List<FileItem> fileItems = upload.parseRequest(req);
			for(FileItem item:fileItems){
				if(item.isFormField()){
					String name=item.getFieldName();
					String value=item.getString();
					String value=item.getString("utf-8");//防止中文乱码
					System.out.println(name+":"+value);
				}else{
					String name=item.getName();
					InputStream in=item.getInputStream();
					String path=getServletContext().getRealPath("/upload");
					System.out.println(path);
					OutputStream out=new FileOutputStream(path+"/"+name);
					int len=0;
					byte[] b=new byte[1024];
					while((len=in.read(b))!=-1){
						out.write(b,0,len);
					}
					in.close();
					out.close();
					
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
  • ServletFileUpload:相关API以下
    • public static final boolean isMultipartContent( HttpServletRequest request) :判断表单提交上来的数据内容是不是multipart类型的数据,即 form表单的 enctype="multipart/form-data",是则返回true,不然返回false
    • public List /* FileItem */ parseRequest(HttpServletRequest request):解析request对象,返回一个泛型为FileItem 的List集合
    • public void setFileSizeMax(long fileSizeMax):设置单个文件的空间大小的最大值
    • public void setSizeMax(long sizeMax):设置全部文件空间大小之和的最大值
    • public void setHeaderEncoding(String encoding):解决上传文件名的乱码问题
    • public void setProgressListener(ProgressListener pListener):上传时的进度条。
  • FileItem:封装表单中提交的数据
    • boolean isFormField():判断当前FileItem对象是表单中提交的文本数据项,仍是文件数据项
    • String getFieldName():获取文本项类型FileItem对象的name属性值,即至关于表单中的 <input type="text" name="name">
    • String getString( String encoding ):获取文本项类型FileItem对象的value值,能够指定编码格式,也能够省略encoding不写
    • String getName():应用于文件项类型的FileItem对象,用于获取文件的名称,包括后缀名
    • InputStream getInputStream():获取输入流
    • void delete():删除临时缓存文件(在输入以及输出流关闭后执行)

    3. 实现多文件上传(须要js技术):主要是更改jsp页面,经过js代码来添加多个文件进行上传,服务器代码无需更改浏览器

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'upload.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
    <script type="text/javascript">
    	function run(){
    		var div=document.getElementById("divId");
    		 div.innerHTML+=
    		 "<div><input type='file' name='upload'><input type='button' value='删除' onclick='del(this)'></div>"
    	}
    	function del(presentNode){
    		var div=document.getElementById("divId");
    		div.removeChild(presentNode.parentNode);
    	}
    </script>
    <div>
  	多文件上传<br/>
    <form action="/Servlet/upload" method="post" enctype="multipart/form-data">
    	<input type="button" value="添加" onclick="run()"><br/>
    	<div id="divId">
    	
    	</div>
    	
    	<input type="submit" value="上传">
    </form>
    </div>
  </body>
</html>

    4. 关于文件上传的一些问题:缓存

  • 文件重名可能会产生覆盖效果,能够在处理文件名时生成一个惟一的文件名
  • 若是全部的文件都储存在一个文件夹中,会致使文件夹下文件过多,能够一个用户一个文件夹,或者利用算法目录分离等方法。

3. 文件下载

    1. 传统文件下载方式有超连接下载或者后台程序下载两种方式。经过超连接下载时,若是浏览器能够解析,那么就会直接打开,若是不能解析,就会弹出下载框;然后台程序下载就必须经过两个响应头和一个文件的输入流。服务器

    2. 后台程序下载:app

  • 两个响应头:
    • Content-Type:其值有好比 text/html;charset=utf-8
    • Content-Disposition:其值为 attachment;filename=文件名  以附件形式打开
  • 流:须要获取文件的输入流,而后经过response对象的输出流输出到客户端。
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;

/**
 * @ClassName:DownLoadServlet
 * @Description:文件下载
 * @author: 
 * @date:2018年9月16日
 */
public class DownLoadServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		//获取请求参数,知道要下载那个文件
		String filename=req.getParameter("filename");
		//设置响应头
		String contentType=getServletContext().getMimeType(filename);//依据文件名自动获取对应的Content-Type头
		res.setContentType(contentType);
		res.setHeader("Content-Dispotition", "attachment;filename="+filename);//设置该头,以附件形式打开下载
		//获取文件的输入流
		String path=getServletContext().getRealPath("/download")+"/"+filename;
		FileInputStream in=new FileInputStream(new File(path));
		OutputStream out= res.getOutputStream();
		byte[] b=new byte[1024];
		int len=0;
		while((len=in.read(b))!=-1){
			out.write(b,0,len);
		}
		in.close();
		out.close();
	}
}
相关文章
相关标签/搜索