OutputStream,http流下载文件服务器的文件给客户

package com.ijiuwen.servlet.test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

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

import com.vnetoo.servlet.BaseServlet;
/**
 * 测试下载
 * @author Huangjs
 *
 */

public class DownloadServlet extends BaseServlet {
	private static final long serialVersionUID = -2185467395939996106L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			response.setContentType("application/octet-stream");
			String name = "小营养师.docx",filename="";
			String userAgent=request.getHeader("User-Agent").toUpperCase();
			if (userAgent.indexOf("MSIE") > 0 ||userAgent.indexOf("TRIDENT")>0){
				filename = URLEncoder.encode(name, "UTF-8");//IE浏览器
			}else{ 
				filename = new String(name.getBytes("UTF-8"), "ISO8859-1");
			}
			response.addHeader("Content-Disposition", "attachment;filename=" +filename);
			java.io.OutputStream os = response.getOutputStream();  URL url=new URL("http://192.168.1.61:8082/news/upload/262565713756815.docx");
			URLConnection conn = url.openConnection();
			
			InputStream inStream = conn.getInputStream();
			byte[] b = new byte[1024];
			int i = 0;
			while ((i = inStream.read(b)) > 0) {
				os.write(b, 0, i);
			}
			
			inStream.close();
			os.flush();
			os.close();
			response.setStatus(HttpServletResponse.SC_OK);
			response.flushBuffer();
		} catch (Exception e) {
			log.error("下载文件失败:" + e.getMessage());
		}
	}
}

1、ie和firfox不同

2、URL远程下载并输出了outputstreem,

3、没有优化代码,只用做测试

优秀到卓越
分享到:

前端需要注意的是window.open.该方式导致ie8无法下载。

js请求改为window.location.href=url;即可。

0

这里面有几个问题:

ie11之前的版本可能乱码,ie11将空格改为+号(加号)。firfox无法识别空格等问题

1、URL地址栏使用编码过的

public String getUtfFileName(){
		try {
			return URLEncoder.encode(getFileName(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return getFileName();
		}
	}
下面这句代码解决后面的问题:
String userAgent=request.getHeader("User-Agent").toUpperCase();
		if (userAgent.indexOf("MSIE") > 0 ||userAgent.indexOf("TRIDENT")>0){
			fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
			fileName = fileName.replace("+", " ");
		}else{ 
			fileName = fileName.replace(" ", "_");
			fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
		}	
0
共 2 条   当前1/1页

© 2014 究问社区 copyRight 豫ICP备13003319号-1