当前位置: 技术问答>java相关
用servlet下载文件时,总是将文件直接显示到浏览器内,而不弹出对话框?
来源: 互联网 发布时间:2015-11-14
本文导语: 我拼凑出来一个下载文件用的servlet,可以编译运行,但总是将文件直接显示到浏览器中,如果是文本还好,mp3等文件都是一大堆乱码!大侠们看看问题在哪儿? 好象是response.setHeader("Content-Disposition","attachment; filename=...
我拼凑出来一个下载文件用的servlet,可以编译运行,但总是将文件直接显示到浏览器中,如果是文本还好,mp3等文件都是一大堆乱码!大侠们看看问题在哪儿?
好象是response.setHeader("Content-Disposition","attachment; filename="" + filename + """); 这一句没起作用?
package mysvt;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class down extends HttpServlet {
public void doGet (HttpServletRequest req,HttpServletResponse response) throws ServletException, IOException{
String filename = "06.mp3";
String filepath = "D:\my_dir\test\";
// 设置响应头和下载保存的文件名
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename="" + filename + """);
// 打开指定文件的流信息
File f=new File(filepath,filename);
java.io.FileInputStream fileIn =
new java.io.FileInputStream(f);
// 写出流信息
int i;
ServletOutputStream sos = response.getOutputStream();
int i_length = fileIn.available();
byte buf_1[]=new byte[i_length];
while(i_length>0){
fileIn.read(buf_1);
sos.write(buf_1);
i_length=fileIn.available();
}
sos.close();
fileIn.close();
}
}
好象是response.setHeader("Content-Disposition","attachment; filename="" + filename + """); 这一句没起作用?
package mysvt;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class down extends HttpServlet {
public void doGet (HttpServletRequest req,HttpServletResponse response) throws ServletException, IOException{
String filename = "06.mp3";
String filepath = "D:\my_dir\test\";
// 设置响应头和下载保存的文件名
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename="" + filename + """);
// 打开指定文件的流信息
File f=new File(filepath,filename);
java.io.FileInputStream fileIn =
new java.io.FileInputStream(f);
// 写出流信息
int i;
ServletOutputStream sos = response.getOutputStream();
int i_length = fileIn.available();
byte buf_1[]=new byte[i_length];
while(i_length>0){
fileIn.read(buf_1);
sos.write(buf_1);
i_length=fileIn.available();
}
sos.close();
fileIn.close();
}
}
|
response.setHeader("Content-Disposition", "attachment;filename="+Utilities.URLEncode(fileName));
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
ServletOutputStream sos = response.getOutputStream();
FileInputStream fis = new FileInputStream(pathFileName);
int j;
while((j=fis.read())!=-1) {
sos.write(j);
}
sos.close();
fis.close();
return;
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
ServletOutputStream sos = response.getOutputStream();
FileInputStream fis = new FileInputStream(pathFileName);
int j;
while((j=fis.read())!=-1) {
sos.write(j);
}
sos.close();
fis.close();
return;
|
Content-Disposition
改为:
Content-Type
改为:
Content-Type