问题描述:网页始终没有弹出下载附件的下载框。
解决:
<a href="/WEB03/download?filename=视频.flv">视频.flv</a><br>
download.html里的这行代码写错了,应该写为
<a href="/WEB03/servlet1?filename=视频.flv">视频.flv</a><br>
因为我的java代码的xml配置文件里的url-pattern是/servlet1,没有/download。
2.文件名乱码问题
不同的浏览器,它对文件名的编码方式不同。所以,服务器要根据浏览器发来的请求头进行解析,判断它是哪个浏览器,再根据相应的浏览器的编码方式来对文件名进行编码。
//将文件名改为utf-8编码方式
filename=new String(filename.getBytes("ISO8859-1"), "UTF-8");
String agent = request.getHeader("User-Agent");
String Filename="";//要另外建一个名字,因为是给浏览器下载附件的文件名称用的
if(agent.contains("MSIE")) {
Filename=URLEncoder.encode(filename, "utf-8");
Filename=Filename.replace("+", "");
}else if(agent.contains("Firefox")) {
BASE64Encoder base64Encoder = new BASE64Encoder();
Filename = "=?utf-8?B?"
+ base64Encoder.encode(filename.getBytes("utf-8"))
+ "?=";
} else {
Filename = URLEncoder.encode(filename, "utf-8");
}
String encode = URLEncoder.encode(filename, "utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + Filename);
String path=this.getServletContext().getRealPath("download/"+filename);
-
验证码
完整代码
package com.ryan.line;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得要下载的文件的名称
String filename=request.getParameter("filename");
//要下载的这个文件的类型----客户端通过文件的MIME类型去区分类型
response.setContentType(this.getServletContext().getMimeType(filename));
//告诉客户端该文件不是直接解释,而是以附件形式打开(下载)
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + new String(filename.getBytes("GBK"), "ISO8859-1"));
String path=this.getServletContext().getRealPath("download/"+filename);
InputStream inputStream=new FileInputStream(path);
//通过字节输出流把图片输出到网页内
ServletOutputStream outputstream=response.getOutputStream();
int len=0;
byte[] buffer=new byte[1024];
while((len=inputStream.read(buffer))>0) {
outputstream.write(buffer, 0, len);
}
//inputstream要关因为它是我们自己new的
inputStream.close();
//outputstream.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}