2--Web 服務器希望瀏覽器不直接處理相應的實體內容,而是由用戶選擇將相應的實體內容保存到一個文件中,這需要設置 Content-Disposition 報頭。該報頭指定了接收程
序處理數據內容的方式,在 HTTP 應用中只有 attachment 是標準方式,attachment 表示要求用戶干預。在 attachment 後面還可以指定 filename 參數,該參數是服務
器建議瀏覽器將實體內容保存到文件中的文件名稱。在設置 Content-Dispostion 之前一定要指定 Content-Type
response.setContentType("application/x-msdownload");
String st="attachment;filename="+java.net.URLEncoder.encode(fileName,"UTF-8");
response.setHeader("Content-Disposition",st);
將下載的文件傳遞給客戶端,相應的內容應該當做二進制來處理。應該用方法調用返回ServletOutputStream對象想客戶端寫入文件。、
ServletOutputStream os=reponse.getOutputStream();
byte[ ] data=new byte[1024];
int len=0;
while((len=is.read(data))>0){
os.write(data,0,len);
}
要實現文件下載需要:ListFileServlet.java DownloadServlet.java listfile.jsp
ListFileServlet.java
1.得到保存上傳文件的文件夾
String savepath = this.getServletContext().getRealPath("/WEB-INF/upload");
2. 創建方法,迭歸文件夾下面的所有文件
listFiles(new File(savepath),map);
3. 將Map對象寫入request,傳至listfiles.jsp
listfile.jsp
取出map中的數據,構建URL作爲下載鏈接的href的屬性值
<c:forEach var="current" items="${fileMap }">
<c:url var="fileAddr" value="/servlet/DownloadServlet">
<c:param name="uuidName">${current.key }</c:param>
<c:param name="realName">${current.value}</c:param>
</c:url>
文件名:${current.value }
<a href="${fileAddr }" >下載</a><br/><br/>
</c:forEach>
DownloadServlet.java
1. 從request中讀取文件名等信息。中文字符使用的URLEncoding,需要進行手動編碼轉換。
String uuidName=request.getParameter("uuidName");
String realName=request.getParameter("realName");
因爲參數是通過url傳過來的,所以需要手動進行編碼轉換
uuidName=new String(uuidName.getBytes("iso8859-1"),"utf-8");
realName=new String(realName.getBytes("iso8859-1"),"utf-8");
因爲realName需要放到response的頭contetn-dispposition中去,發送到客戶的瀏覽器端,所以需要對它調用URLEncoder的encode方法進行url編碼,纔可以保證
客戶取到正確的中文文件名。
realName=URLEncoder.encode(realName,"utf-8");
2. 判斷文件是否存在
if(!file.exists()){
request.setAttribute("message", "您要下載的文件不存在!");
request.getRequestDispatcher("/message.jsp").forward(request, response);
}else{
response.setHeader("content-disposition", "attachment;filename="+realName);
3. 獲取輸入流,並寫入輸出流
FileInputStream fis = new FileInputStream(file);
OutputStream out = response.getOutputStream();
byte [ ] buffer = new byte[1024];
int len = 0;
while((len=fis.read(buffer))>0){
out.write(buffer, 0, len);
}
fis.close();
4.設置一二級目錄,獲取文件地址
int dir1 = uuidName.hashCode() & 0xf;
int dir2 =(uuidName.hashCode()>>4) & 0xf;
String fileAddr = this.getServletContext().getRealPath("/WEB-INF/upload") +"\\" + dir1 + "\\" + dir2 + "\\" + uuidName;