java下載文件代碼示例

@RequestMapping("download")
public void dowanload(HttpServletRequest request,HttpServletResponse response) throws IOException{
String filePath="H:/photo/a.docx";
//支持在線打開文件的一種方式  
        File f = new File(filePath);  
        if (!f.exists()) {  
            response.sendError(404, "File not found!");  
            return;  
        }  
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));  
        byte[] buf = new byte[1024];  
        int len = 0;  
        response.reset(); // 非常重要  
        response.setContentType("application/x-msdownload");  
        response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());  
        OutputStream out = response.getOutputStream();  
        while ((len = br.read(buf)) > 0)  
            out.write(buf, 0, len);  
        br.close();  
        out.close();  
}
發佈了31 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章