現在已經寫好了用于下載的servlet如下:
String fileName = request.getParameter("filename");
//下載檔案:設定回應訊息頭
response.addHeader("content-type","application/octet-stream");
response.addHeader("content-disposition","attachment;filename="+fileName);
//拼接檔案路徑
String path = this.getServletContext().getRealPath("res/"+fileName);
//Servlet通過檔案地址 將檔案轉為輸入流 讀到Servlet中
FileInputStream in = new FileInputStream(path);但是其中filename獲取的時候在前頁必須指定好該檔案的名稱和格式型別,如:
<a href="https://bbs.csdn.net/topics/Downloadservlet?filename=.doc">下載該檔案</a>
現在由于專案需要服務器中的檔案格式型別不定,因此這個方法就失效了。請問各位大佬有什么方法可以解決嗎?盡量在我這個方法框架之內實作,感激不盡!!
uj5u.com熱心網友回復:
public void download(InModel inModel, String path, HttpServletResponse response) throws Exception {
response.setContentType("application/octet-stream");
response.addHeader("Content-disposition", "attachment;filename=" + path.substring(path.lastIndexOf("/")));
OutputStream outputStream = null;
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
outputStream = response.getOutputStream();
File file = new File(''地址");
inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, outputStream);
} catch (Exception ex) {
//logger
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.close(conn);
IOUtils.closeQuietly(outputStream);
}
}這樣?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/64715.html
標籤:Web 開發
