public Boolean downloadFile(String id, String name, HttpServletRequest request, HttpServletResponse response){ //根据ID查询文件是否存在 FileUpload upload = gridFSUploadDao.findOne(id); if(CommentUtils.isEmpty(upload)){ throw new BadRequestException(ExceptionEnum.FILE_NOT_FOUND.getMessage()); } //将下载操作记录至文件下载表中 FileDownload download = new FileDownload(); download.setCreateTime(DateUtils.dateToISODate(new Date())); download.setUpdateTime(DateUtils.dateToISODate(new Date())); download.setFileName(upload.getFileName()); download.setFileId(upload.getGridId()); download.setOperator(name); download.setDelete(false); gridFSDownloadDao.insertDownload(download); Query query = Query.query(Criteria.where("_id").is(upload.getGridId())); byte[] resource = GridFsUtils.downloadFile(mongoTemplate,gridFsTemplate,query); byte[] buffer = new byte[1024]; ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(resource); try { OutputStream out = response.getOutputStream(); int i = byteArrayInputStream.read(buffer); while (i != -1) { out.write(buffer, 0, i); i = byteArrayInputStream.read(buffer); } out.flush(); System.out.println("********************下载success**************"); } catch (IOException e) { e.printStackTrace(); }finally { if (byteArrayInputStream != null) { try { byteArrayInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } // OutputStream os = null; // InputStream is= null; // try { // // 取得输出流 // os = response.getOutputStream(); // // 清空输出流 // response.reset(); // response.setContentType("multipart/form-data"); // response.setHeader("Content-Disposition", "attachment;filename="+ new String(upload.getFileName().getBytes("utf-8"), "iso-8859-1")); // response.addHeader("Content-Length", "" + upload.getFileSize()); // is = resource.getInputStream(); // //复制 // IOUtils.copy(is, response.getOutputStream()); // response.getOutputStream().flush(); // log.info("********************下载success**************"); // } catch (Exception e) { // throw new BadRequestException(e.getMessage()); // // }finally { // try { // if (is != null) { // is.close(); // } // } catch (IOException e) { // log.error(ExceptionUtils.getFullStackTrace(e)); // } // try { // if (os != null) { // os.close(); // } // } catch (IOException e) { // log.error(ExceptionUtils.getFullStackTrace(e)); // } // } return true; }