springmvc下载实现

/**.
	 * 下载
	 * @param req
	 * @param response
	 * @param id
	 * @throws Exception
	 */
	@RequestMapping("/download/{id}")
	public void download(HttpServletRequest req, HttpServletResponse response,@PathVariable int id)
			throws Exception { 
         
        req.setCharacterEncoding("UTF-8"); 
        BufferedInputStream bis = null; 
        BufferedOutputStream bos = null; 
        
       // int fileId=getParam2int(req, "fileId");
        int fileId=id;
        //文件信息
        Map<String, Object> fileInfo =mainService.getFileInfo(fileId);
   
        //获取文件路径
        String downLoadPath = fileInfo.get("filePath").toString();
            
        //获取文件的长度
        long fileLength = new File(downLoadPath).length(); 
        //文件名
        String fileName=fileInfo.get("fileName").toString();
 
        //设置文件输出类型
        response.setContentType("application/octet-stream"); 
        response.setHeader("Content-disposition", "attachment; filename=" 
                + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        //设置输出长度
        response.setHeader("Content-Length", String.valueOf(fileLength)); 
        //获取输入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath)); 
        //输出流
        bos = new BufferedOutputStream(response.getOutputStream()); 
        byte[] buff = new byte[2048]; 
        int bytesRead; 
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { 
            bos.write(buff, 0, bytesRead); 
        } 
        //关闭流
        bis.close(); 
        bos.close(); 
    }


发布了37 篇原创文章 · 获赞 8 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_34122822/article/details/77988412