您的位置:首页 > 编程语言 > Java开发

java下载文件代码示例

2017-07-31 11:19 471 查看
@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();  
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: