springmvc下载实现

来源:互联网 发布:unity3d 素材制作 编辑:程序博客网 时间:2024/05/29 08:02
/**. * 下载 * @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();     }


原创粉丝点击