现在网上的文章都是用的低版本的jar包,而最新的jar包,下载的方法进行了改变。在网上也没找到好的方法。就用原生的方法进行下载,
我也不知道对不对。反正可以下载了。就先这样吧。后期准备还是用低版本的开发比较好。至少网上文章多。
http下载。主要获取数据库的内容,输入流。然后获取响应的输出流。
用输出流给网页。进行下载。
@ResponseBody @RequestMapping("/download") public void download(HttpServletResponse response){ GridFSFile fs = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is("5c0605554a24a322dfea107d"))); try { byte bs[]=new byte[1024]; GridFsResource resource = gridFsTemplate.getResource(fs); InputStream inputStream = resource.getInputStream(); ServletOutputStream outputStream = response.getOutputStream(); response.setContentType("application/octet-stream"); response.setHeader("Content-disposition","attachment;filename="+resource.getFilename()); while (inputStream.read(bs)>0){ outputStream.write(bs); } inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } }
低版本
/* * 下载文件。传入文件id * */ @RequestMapping(value = "/files/download/{id}") public void getDownload(@PathVariable String id, HttpServletResponse response){ try { Resource resource=resourceService.get(id); if (resource!=null){ if (resource.getType()==1){ GridFSDBFile file = fileService.getFile(resource.getFileId()); if (file!=null){ response.setContentType("application/octet-stream"); OutputStream out = response.getOutputStream(); response.setHeader("Content-disposition","attachment;filename="+file.getFilename()); file.writeTo(out); out.flush(); out.close(); } }else { } } }catch (Exception e){ } }