日期:2014-05-17  浏览次数:20819 次

java文件下载,怎么让用户选择“保存”或“打开”,而不是直接下载?
如题,用IE测试时,有时直接就用迅雷下载了,不会弹出那个“保存”或“打开”的对话框
下面是servlet代码
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");

String fileName = request.getParameter("fileName");
fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8").trim();//文件名

String path = request.getRealPath("/")+"webs/";
String target = path+"file"+File.separator+"workflow"+File.separator+fileName;//文件存储的位置
String fileType = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());

response.reset(); //清空response
response.setHeader("Content-Disposition", "attachment;filename="+fileName);

OutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(target);
try {
fileName = URLEncoder.encode(fileName, "utf-8");
fileType.toLowerCase();
if("ceb".equals(fileType)){ 
response.setContentType("application/x-ceb");
}else if("doc".equals(fileType)){
response.setContentType("application/msword");
}else if("xls".equals(fileType)){
response.setContentType("application/vnd.ms-excel");
}else if("gif".equals(fileType)){
response.setContentType("image/gif");
}else if("bmp".equals(fileType)){
response.setContentType("image/bmp");
}else if("jpeg".equals(fileType)){
response.setContentType("image/jpeg");
}else if("txt".equals(fileType)){
response.setContentType("text/plain");
}else if("pdf".equals(fileType)){
response.setContentType("application/pdf");
}else if("jpeg".equals(fileType)){
response.setContentType("image/jpeg");
}else{
response.setContentType("application/octet-stream");
}

int n = 0;
byte b[] = new byte[1024];
while ((n = in.read(b)) != -1)
{
out.write(b, 0, n);
}
out.flush();
}catch(Exception e) {
e.printStackTrace();
}finally{
if(in != null) {
in.close();
}
if(out != null) {
out.close();
}
}
}

------解决方案--------------------
我也遇到通过迅雷下载....后来发现是和迅雷设置还是浏览器设置有关。应该是迅雷.你设置一下迅雷应该就不通过迅雷下载了.你可以试试。具体设置迅雷那个属性我也忘记了 囧
------解决方案--------------------
迅雷设置里面有个设为浏览器默认下载工具,取消就ok了
------解决方案--------------------
貌似是迅雷监视设置里面监视浏览器勾掉就可以。
------解决方案--------------------
工具下载跟代码没关系!