vue附件下载

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();
        }
    }

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);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1296390.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存