03_比较正式的文件下载

一、下载过程

比较正式的文件下载,文件上传时被加密后,存储到服务里的某个路径下。
在这里插入图片描述
下载时,用户点击下载按钮,前端发送post请求,参数json对象到后端。

二、后端

在这里插入代码片
   @RequiresPermissions({"attachment:fileDownload"})
    @RequestMapping({"/fileDownload"})
    @ResponseBody
    public void fileDownload(HttpServletResponse response) {
        String fileId = super.getPara("fileId");
        String appType = super.getPara("dbName");
        String title = super.getPara("title");
        String secretFile = super.getPara("secretFile");
        new AttachmentManagerModel();

        AttachmentManagerModel attachmentModel;
        try {
            this.changeTenantDs(appType);
            attachmentModel = (AttachmentManagerModel)this.attachmentManagerService.getById(fileId);
        } finally {
            DataSourceUtil.poll();
        }

        String id = attachmentModel.getId();
        String fileName = attachmentModel.getAttachmentName();
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        String encryptKey = attachmentModel.getEncrypt();
        String path;
        if (ToolUtil.isNotEmpty(attachmentModel.getEncrypt())) {
            FileEncryptUtil feu = FileEncryptUtil.getInstance();
            String pathEncrypt = attachmentModel.getAttachmentDir() + id + prefix + ".encrypt";
            path = attachmentModel.getAttachmentDir() + id + prefix;
            feu.decrypt(pathEncrypt, path, encryptKey.trim());
        } else {
            path = attachmentModel.getAttachmentDir() + id + prefix;
        }

        try {
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)), 10240);
            Throwable var93 = null;

            try {
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
                Throwable var15 = null;

                try {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                    response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
                    response.setContentType("multipart/form-data");
                    int len = false;
                    int i = bis.available();
                    byte[] buff = new byte[i];

                    int len;
                    while((len = bis.read(buff)) > 0) {
                        out.write(buff, 0, len);
                        out.flush();
                    }

                    Map<String, String> info = new HashMap();
                    info.put("sessionId", (String)ShiroKit.getSession().getId());
                    info.put("ip", HttpKit.getIp());
                    info.put("port", HttpKit.getPort());
                    info.put("host", HttpKit.getHost());
                    info.put("localIp", HttpKit.getLocalIp());
                    info.put("localPort", HttpKit.getLocalPort());
                    info.put("localHost", HttpKit.getLocalHost());
                    info.put("title", title);
                    info.put("action", "附件下载");
                    info.put("fileName", secretFile);
                    HussarLogManager.me().executeLog(LogTaskFactory.fileLog(ShiroKit.getUser(), "19", info));
                } catch (Throwable var84) {
                    var15 = var84;
                    throw var84;
                } finally {
                    if (out != null) {
                        if (var15 != null) {
                            try {
                                out.close();
                            } catch (Throwable var82) {
                                var15.addSuppressed(var82);
                            }
                        } else {
                            out.close();
                        }
                    }

                }
            } catch (Throwable var86) {
                var93 = var86;
                throw var86;
            } finally {
                if (bis != null) {
                    if (var93 != null) {
                        try {
                            bis.close();
                        } catch (Throwable var81) {
                            var93.addSuppressed(var81);
                        }
                    } else {
                        bis.close();
                    }
                }

            }
        } catch (FileNotFoundException var88) {
            logger.error("文件未找到" + var88.getMessage());
            throw new HussarException(BizExceptionEnum.FILE_NOT_FOUND);
        } catch (UnsupportedEncodingException var89) {
            logger.error("不支持的编码异常:" + var89.getMessage());
            throw new HussarException(BizExceptionEnum.DOWNLOAD_ERROR);
        } catch (IOException var90) {
            logger.error("IO异常:" + var90.getMessage());
            throw new HussarException(BizExceptionEnum.DOWNLOAD_ERROR);
        } finally {
            try {
                FileUtils.forceDelete(new File(path));
            } catch (IOException var80) {
                var80.printStackTrace();
            }

        }
    }

三、前端

在这里插入代码片
       let obj = {
          fileId: fileId,
          dbName: dbName,
          title: title,
          secretFile: secretFile
        };// 这4个参数传给后端

        let file = {
          fileName: secretFileH,//imag.png
          securityLevelLabel: secretFileQ //'公开'
        };

        //下载请求开始
        hussarRequest.download('/attachment/fileDownload', obj).then(res => {
          const content = res;

          const blob = new Blob([content]);
          const fileName = file.fileName;
          const securityLevelLabel = file.securityLevelLabel;
          if ('download' in document.createElement('a')) {
            const elink = document.createElement('a');
            if (!securityLevelLabel) {
              elink.download = fileName;
            } else {
              elink.download = '(' + securityLevelLabel + ')' + fileName;
            }
            elink.style.display = 'none';
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName);
          }
          if (callback && typeof callback === 'function') {
            callback();
          }
        }).catch(res => {
          console.error(res.msg);
        })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值