栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

vue附件下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

vue附件下载

  1. a标签下载

    
    {{ file.name }}  
    
       
        @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,所以需要使用该方式)

     {{ file.name }}  
         
      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);
    }
    
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/921675.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号