最近做一个下载文件,下载到指定的目录下面,发现下载后文件只会保存的服务端指定的目录,这就很鸡肋,因此总结一下下载的感想,下面方法可套用于下载任何文件,也可用于下载保存在数据库的文件。
特别注意:前端页面请求不能使用Ajax,可以使用a便签
首先看原先鸡肋的代码:
String path="D:\\javamyWorkSpaceEclipse\\DownLoad\\WebRoot\\images\\1.png";
FileOutputStream fileOutputStream =null;
InputStream fis =null;
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
fis= new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
//D:\\download为指定下载到该目录下
fileOutputStream= new FileOutputStream("D:\\download\\"+filename);
fileOutputStream.write(buffer);
} catch (Exception ex) {
ex.printStackTrace();
}finally {
if(fis!=null) {
fis.close();
}
if(fileOutputStream!=null) {
fileOutputStream.close();
}
}
正确的下载方式:
String realPath = request.getServletContext().getRealPath("images");
String path=realPath+"\\0803046.V3";
OutputStream toClient =null;
InputStream fis = null;
try {
/* 下面是从需要下载的地方将文件以流的形式读取出来,这里根据不同需求不一样的写法,如果是ftp下载的话这一部分需要另外写,此处只是模拟 */
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
/* 下面是将读取出的流放到response的输出流中 */
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}finally {
if(fis!=null) {
fis.close();
}
if(toClient!=null) {
toClient.close();
}
}