1. 程式人生 > >Java的檔案下載(通用)

Java的檔案下載(通用)

/**
* 下載檔案

* @param request
* @param response
* @return
*/
@RequestMapping(params = "downLoadFile")
public void downLoadFile(HttpServletRequest request, HttpServletResponse response) {
String localPath = getLocalPath();//這是本地上傳路徑(例如:D:/upload)
String filePath = getFilePath();//這個是web專案的相傳路徑,存資料庫(例如:/uoload)
String path = request.getParameter("path");
String fileName = request.getParameter("fileName");
filePath = path.replaceFirst(filePath, localPath);//將資料庫的檔案上傳路徑改為本地的上傳路徑
File file = new File(filePath);
if(fileName == null || fileName.equals("")){
fileName = file.getName();
}
BufferedInputStream in = null;
ServletOutputStream out = null;
byte[] b;
if (!file.exists() || !file.isFile()) {
system.out.println("檔案不存在,下載失敗!");
}
response.reset();
// 1.設定檔案ContentType型別,這樣設定,會自動判斷下載檔案型別
response.setContentType("multipart/form-data");
// 2.設定檔案頭:最後一個引數是設定下載檔名(假如我們叫a.pdf)
try {
response.setHeader("Content-Disposition",
"attachment;fileName=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
response.setCharacterEncoding("utf-8");
in = new BufferedInputStream(new FileInputStream(file));
b = new byte[1024];
out = response.getOutputStream();
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
} catch (UnsupportedEncodingException e2) {
e2.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}