这里贴一下主要代码
首先根据id查询从数据库查询文件记录信息
在浏览器访问这个请求后,浏览器会弹出下载
首先根据id查询从数据库查询文件记录信息
- /**
- * 下载
- * @param id 文件ID
- * @param request
- * @param response
- * @throws IOException
- */
- @GetMapping(value = "/attachment/download")
- public void downloadFile(@RequestParam("id") String id,
- HttpServletRequest request, HttpServletResponse response) throws IOException {
- Attachment attachment = attachmentService.findById(id);
- if (attachment != null) {
- InputStream f = new FileInputStream(new File(attachment.getPath()));
- response.reset();
- response.setContentType("application/x-msdownload;charset=utf-8");
- response.setHeader("Content-Disposition", "attachment;filename=" + attachment.getName() + "." + attachment.getSuffix());//下载文件的名称
- ServletOutputStream sout = response.getOutputStream();
- BufferedInputStream bis = null;
- BufferedOutputStream bos = null;
- try {
- bis = new BufferedInputStream(f);
- bos = new BufferedOutputStream(sout);
- byte[] buff = new byte[2048];
- int bytesRead;
- while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
- bos.write(buff, 0, bytesRead);
- }
- bos.flush();
- bos.close();
- bis.close();
- } catch (final IOException e) {
- throw e;
- } finally {
- if (bis != null) {
- bis.close();
- }
- if (bos != null) {
- bos.close();
- }
- }
- }
- }
在浏览器访问这个请求后,浏览器会弹出下载
您可以选择一种方式赞助本站
支付宝扫一扫赞助
微信钱包扫描赞助
赏