用Response實現檔案下載
這個由於自己的一個失誤導致瀏覽器一直讀取不到檔名和檔案型別,後來發現是一個筆誤。
"attachment;filename="+filename 少寫了一個等號。。。。把這個程式碼貼上來,以此記錄。
直接帖程式碼
/**
* Response實現檔案下載
*
*/
public class FileDownload extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse respose) throws ServletException,IOException{
String path=this.getServletContext().getRealPath("/download/1.jpg");
String filename=path.substring(path.lastIndexOf("\\")+1);
respose.addHeader("Content-Disposition", "attachment;filename="+filename);
respose.setHeader("Content-Type", "text/html,charset=utf-8");
InputStream in=null;
OutputStream out=null;
try{
in=new FileInputStream(path);
int len=0;
byte buffer[]=new byte[1024];
out=respose.getOutputStream();
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
System.out.println("path:"+path);
System.out.println("filename:"+filename);
}finally{
if(in!=null){
try{
in.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}