| | |
| | | } catch (Exception ex) { |
| | | return ctrl.fail(ex.getMessage(), null); |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 获取附件实体类 |
| | |
| | | return; |
| | | } |
| | | |
| | | setDownloadResponse(entity, res); |
| | | String filePath = pathHelper.getConfig().getUploadPath() + File.separator + entity.getPath(); |
| | | |
| | | // 通过response对象,获取到输出流 |
| | | ServletOutputStream outputStream = res.getOutputStream(); |
| | | // 定义输入流,通过输入流读取文件内容 |
| | | FileInputStream fileInputStream = new FileInputStream(filePath); |
| | | |
| | | int len = 0; |
| | | byte[] bytes = new byte[1024]; |
| | | while ((len = fileInputStream.read(bytes)) != -1) { |
| | | // 通过输入流读取文件数据,然后通过上述的输出流写回浏览器 |
| | | outputStream.write(bytes, 0, len); |
| | | outputStream.flush(); |
| | | } |
| | | |
| | | // 关闭资源 |
| | | outputStream.close(); |
| | | fileInputStream.close(); |
| | | String file = pathHelper.getConfig().getUploadPath() + File.separator + entity.getPath(); |
| | | WebHelper.download(file, entity.getName(), res); |
| | | } catch (Exception ex) { |
| | | try { |
| | | String msg = JSON.toJSONString(new ResponseMsg<String>(HttpStatus.ERROR, "文件下载出错")); |
| | |
| | | } |
| | | log.error(ex.getMessage(), ex); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 设置下载响应信息 |
| | | */ |
| | | private void setDownloadResponse(AttachEntity entity, HttpServletResponse res) throws IOException { |
| | | String fileName = URLEncoder.encode(entity.getName(), "UTF-8"); |
| | | |
| | | // 设置响应头中文件的下载方式为附件方式,以及设置文件名 |
| | | res.setHeader("Content-Disposition", "attachment; filename=" + fileName); |
| | | // 设置响应头的编码格式为UTF-8 |
| | | res.setCharacterEncoding("UTF-8"); |
| | | |
| | | // 通过response对象设置响应数据格式(如:"text/plain; charset=utf-8") |
| | | String ext = FileHelper.getExtension(entity.getName()); |
| | | String mime = FileHelper.getMime(ext); |
| | | res.setContentType(mime); |
| | | } |
| | | } |