文件下載功能是web開發(fā)中經(jīng)常使用到的功能,使用HttpServletResponse對象就可以實現(xiàn)文件的下載
文件下載功能的實現(xiàn)思路:
1.獲取要下載的文件的絕對路徑
2.獲取要下載的文件名
3.設(shè)置content-disposition響應(yīng)頭控制瀏覽器以下載的形式打開文件
4.獲取要下載的文件輸入流
5.創(chuàng)建數(shù)據(jù)緩沖區(qū)
6.通過response對象獲取OutputStream流
7.將FileInputStream流寫入到buffer緩沖區(qū)
8.使用OutputStream將緩沖區(qū)的數(shù)據(jù)輸出到客戶端瀏覽器
示例:通過Response實現(xiàn)文件下載(以ssm框架controller里接口類為例)
/**下載文件接口 通過OutputStream流
* @param request
* @param response
* @return
*/
@RequestMapping("/product/equipmentVersionQuery/dowloadFile.do")
public void dowloadFile(HttpServletRequest request,HttpServletResponse response){
String languageType = request.getParameter("language");
if(null != languageType && !"".equals(languageType)){
if(languageType.equals("en")){
languageType = "EN";
} else{
languageType = "CN";
}
} else{
languageType = "CN";
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//獲取要下載的文件名
try {
String excelName = AppFrameworkUtil.encodeExcelName(moduleName) + df.format(new Date());
if("EN".equals(languageType)){
excelName = AppFrameworkUtil.encodeExcelName(moduleNameEn) + df.format(new Date());
}
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//設(shè)置content-disposition響應(yīng)頭控制瀏覽器以下載的形式打開文件
response.addHeader("Content-Disposition", "attachment;filename="+excelName+ ".png");
} catch (Exception e) {
e.printStackTrace();
}
//獲取要下載的文件的絕對路徑
String realPath = request.getSession().getServletContext().getRealPath("/images/module/curve_w.png");
InputStream in = null;
OutputStream out = null;
try {
//獲取要下載的文件輸入流
in = new FileInputStream(realPath);
int len = 0;
//創(chuàng)建數(shù)據(jù)緩沖區(qū)
byte[] buffer = new byte[1024];
//通過response對象獲取outputStream流
out = response.getOutputStream();
//將FileInputStream流寫入到buffer緩沖區(qū)
while((len = in.read(buffer)) > 0) {
//使用OutputStream將緩沖區(qū)的數(shù)據(jù)輸出到瀏覽器
out.write(buffer,0,len);
}
out.flush();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
也可以下載到服務(wù)器指定位置 通過BufferedOutputStream
/**下載文件到服務(wù)器指定位置 通過BufferedOutputStream
* @param request
* @param response
* @return
*/
@RequestMapping("/product/equipmentVersionQuery/dowloadFile.do")
public void dowloadFile(HttpServletRequest request,HttpServletResponse response){
//獲取要下載的文件絕對路徑
String realPath = request.getSession().getServletContext().getRealPath("/images/module/curve_w.png");
InputStream in = null;
OutputStream out = null;
try {
File file = new File(request.getSession().getServletContext().getRealPath("/") + "/demoExcel/img.png");
if(!file.exists())
{
file.createNewFile();
}
//創(chuàng)建BufferedOutputStream流
out = new BufferedOutputStream(new FileOutputStream(file));
in = new FileInputStream(realPath);
int len = 0;
//創(chuàng)建數(shù)據(jù)緩沖區(qū)
byte[] buffer = new byte[1024];
//將FileInputStream流寫入到buffer緩沖區(qū)
while((len = in.read(buffer)) > 0) {
//使用BufferedOutputStream將緩沖區(qū)的數(shù)據(jù)輸出到指定位置文件
out.write(buffer,0,len);
}
out.flush();
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
如果是導(dǎo)出excel到指定位置就簡單的多,直接用創(chuàng)建好返回的workbook對象寫入到輸出流輸出就好了
wb.write(out);
如:
//創(chuàng)建指定目錄文件
File f = new File(request.getSession().getServletContext().getRealPath("/") + "/demoExcel/demo.xls");
if(!f.exists())
{
f.createNewFile();
}
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
wb.write(out);
//關(guān)閉流
out.flush();
out.close();
補充:
如果是下載到瀏覽器不知道是什么類型的文件的話,可以設(shè)置response表頭:
/* 設(shè)置文件ContentType類型,這樣設(shè)置,會自動判斷下載文件類型 */
response.setContentType("multipart/form-data");
例如:
public void downloadFile(File file, HttpServletRequest request, HttpServletResponse response,String
nameString ,String suffixName) throws Exception {
boolean success = false;
InputStream fis = new FileInputStream(file);
/* 設(shè)置文件ContentType類型,這樣設(shè)置,會自動判斷下載文件類型 */
response.setContentType("multipart/form-data");
//response.setContentType("application/OCTET-STREAM;charset=UTF-8");
/* 設(shè)置文件頭:最后一個參數(shù)是設(shè)置下載文件名 */
String formFileName = new String(nameString.getBytes("UTF-8"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + formFileName + "." +suffixName);
try {
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024 * 1024 * 200];
int len;
while ((len = fis.read(b)) > 0) {
os.write(b, 0, len);
}
os.flush();
os.close();
fis.close();
success=true;
} catch (Exception e) {
success = false;
e.printStackTrace();
}
}