vue附件下载

  1. a标签下载

    <a :href="地址" :download="file.name" :underline="false" target="_blank">
    {{ file.name }}  </a>
    
       /**
         * 根据主键获得commonAttachment.
         */
        @ApiOperation(value = "下载附件", notes = "")
        @RequestMapping(path = "/uploadById", method = RequestMethod.GET)
        @CrossOrigin
        public void uploadById(HttpServletRequest request, HttpServletResponse response, String id) {
            log.debug("下载附件");
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
    
            try {
                InputStream fis=null;
                File file =null;
                if(id!=null&&!"".equals(id)){
                    String newfilename=null;
                    String allPath=null;
                    CommonAttachment attachment = commonAttachmentService.getById(id);
                    newfilename = attachment.getFileName();
                    //附件存在本地,本地路径+相对路径
                    allPath = ConstantDB.REPOTR_LOG_DIR + attachment.getFilePath();
                    // path是指欲下载的文件的路径。
                    file = new File(allPath);
                    fis= new BufferedInputStream(new FileInputStream(allPath));
    
                    byte[] buffer = new byte[fis.available()];
                    fis.read(buffer);
                    fis.close();
                    // 清空response
                    response.reset();
                    // 设置response的Header
                    response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(newfilename, "UTF-8"));
                    OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                    response.setContentType("application/octet-stream");
                    toClient.write(buffer);
                    toClient.flush();
                    toClient.close();
                }
            } catch(FileNotFoundException e){
                System.out.println("---------文件下载失败,该文件不存在。-----------");
            }catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    
  2. axios下载(由于a标签无法携带token,所以需要使用该方式)

     <a @click="downloadFile(`${file.id}`,`${file.name}`)">{{ file.name }}  </a>
         
      axios({
            method: 'get',
            url: url,
            responseType: 'blob',
            headers: {Authorization: token}
          }).then(res => {
            const {data} = res
            const blob = new Blob([data])
            let disposition = decodeURI(res.headers['content-disposition'])
            // 从响应头中获取文件名称
            if ('download' in document.createElement('a')) {
              // 非IE下载
              const elink = document.createElement('a')
              elink.download = name
              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, name)
            }
          }).catch((error) => {
            console.log(error)
          })
    
    try {
        if (id == null) {
            throw new Exception(StringUtils.format("资源文件id({})为空,不允许下载。 ", id));
        }
        CommonAttachment attachment = commonAttachmentService.getById(id);
        if (attachment == null) {
            throw new Exception(StringUtils.format("非找到id的({})的资源文件,不允许下载。 ", id));
        }
        // 数据库资源地址,本地+相对
        String downloadPath = ConstantDB.REPOTR_LOG_DIR + attachment.getFilePath();
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, attachment.getFileName());
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    } catch (Exception e) {
        log.error("下载文件失败", e);
    }
    
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值