HttpServletResponse下载文件(中文名称下载)-------手动编码实现下载

HttpServletResponse下载文件(中文名称下载)-------手动编码实现下载_第1张图片

DownloadServlet:
 

package com.yuming.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

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


import com.yuming.util.Base64Util;

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {

		protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
			//1. 获取要下载的文件名字 aa.jpg  --- inputStream
			String fileName = request.getParameter("filename");
			
			//get请求,这个fileName有中文
			fileName = new String(fileName.getBytes("UTF-8"),"UTF-8");
			System.out.println("fileName="+fileName);
			
			
			//2. 获取这个文件在tomcat里面的绝对路径地址
			String path = getServletContext().getRealPath("download/"+fileName);
			
			/**
			 * 如果文件的名字带有中文,需要对文件名进行编码处理
			 * 
			 * IE/chrome 使用URLEncoding编码
			 * 
			 * Firefox ,使用base64 编码
			 */
			String clientType = request.getHeader("User-Agent");
			if(clientType.contains("Firefox")){
				fileName = Base64Util.base64EncodeFileName(fileName);
			}else{
				//IE ,或者  Chrome (谷歌浏览器) ,
				//对中文的名字进行编码处理
				fileName = URLEncoder.encode(fileName, "UTF-8");
			}
			
			//让浏览器收到这份资源的时候, 以下载的方式提醒用户,而不是直接展示。 
			response.setHeader("Content-Disposition", "attachment; filename="+fileName);
			
//			response.setStatus(302);
//			response.setHeader("Location", "login_success.html");
			
			//
			//response.sendRedirect("login_success.html");
			
			//3. 转化成输入流
			InputStream is = new FileInputStream(path);
			OutputStream os = response.getOutputStream();
			
			int len = 0 ;
			byte[]buffer = new byte[1024];
			while( (len = is.read(buffer)) != -1){
				os.write(buffer, 0, len);
			}
			
			os.close();
			is.close();
		
		}

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

Base64Util:
 

package com.yuming.util;

import java.io.UnsupportedEncodingException;

import sun.misc.BASE64Encoder;

public class Base64Util {
	
	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);
		}
	}

}

web.xml:
 



	Download
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	
	
		
		DownloadServlet
		DownloadServlet
		com.yuming.servlet.DownloadServlet
	
	
		DownloadServlet
		/DownloadServlet
	

download.html:
 





Insert title here



	

tomcat默认servlet提供下载

aa.jpg
bb.txt
cc.rar

手动编码提供下载。:
aa.jpg
bb.txt
cc.rar
大海.jpg

 

 谷歌,火狐都可以下载哟...

 有个问题,求解

换成ISO-8859-1之后:

HttpServletResponse下载文件(中文名称下载)-------手动编码实现下载_第2张图片

HttpServletResponse下载文件(中文名称下载)-------手动编码实现下载_第3张图片

 

控制台报错 :

十二月 21, 2018 10:16:39 上午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [DownloadServlet] in context with path [/Download] threw exception
java.lang.NullPointerException
	at java.io.FileInputStream.(FileInputStream.java:130)
	at java.io.FileInputStream.(FileInputStream.java:93)
	at com.yuming.servlet.DownloadServlet.doGet(DownloadServlet.java:62)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:748)

fileName=??.jpg

 

你可能感兴趣的:(HttpServletResponse下载文件(中文名称下载)-------手动编码实现下载)