当前位置 : 主页 > 编程语言 > c++ >

DownloadServlet.java

来源:互联网 收集:自由互联 发布时间:2021-07-03
DownloadServlet.java package cn.web.servlet;import java.io.FileInputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import javax.servlet.ServletException;import javax.servlet.ServletO
DownloadServlet.java
package cn.web.servlet;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

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

import sun.misc.BASE64Encoder;

public class DownloadServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		//1.1获取下载资源文件的名称
		String filename = request.getParameter("filename");
		
		//1.2 解决中文乱码问题
		filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
		
		// 2.获取下载文件的路径
		String realPath = this.getServletContext().getRealPath("download/"+filename);
		System.out.println(realPath);
		
		//3.设置两个头(ContentType和Content-Disposition)
			//3.1 先得获取ContentType的内容(MIME类型)
		String mimeType = this.getServletContext().getMimeType(filename);
		//System.out.println(mimeType);
			//3.2设置contentType
		response.setHeader("ContentType", mimeType);
		
			//3.3解决下载框中文(根据不同的浏览器设置不同的解决方式)
		String user_Agent = request.getHeader("User-Agent");
		if(user_Agent.contains("Firefox")){ //解决火狐的
			filename = base64EncodeFileName(filename);
		}else{
			filename = URLEncoder.encode(filename, "UTF-8");
		}
		
		//3.4 设置Content-Disposition内容  告诉浏览器请使用下载框的方式打开该文件
		response.addHeader("Content-Disposition", "attachment;filename="+filename);
		
		// 4.获得输入一个流
		FileInputStream is = new FileInputStream(realPath);
		// 5.获得一个输出流
		ServletOutputStream os = response.getOutputStream();
		// 6.输入流输出流对拷
		int len = 0;
		byte[] b = new byte[1024];
		while ((len = is.read(b)) != -1) {
			os.write(b, 0, len);
		}
		os.close();
		is.close();
	}

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

	/**
	 * 解决火狐浏览器乱码问题
	 * @param fileName
	 * @return
	 */
	public static String base64EncodeFileName(String fileName) {
		BASE64Encoder base64Encoder = new BASE64Encoder();
		try {
			return "=?UTF-8?B?"
					+ new String(base64Encoder.encode(fileName
							.getBytes("UTF-8"))) + "?=";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
}
网友评论