前端如何获取响应头Content-Disposition中的filename,获取文件类型fileType进行不同类型的文件预览

文章介绍了如何使用axios从服务器获取文件,通过content-disposition头判断文件类型,然后针对不同类型的文件(如PDF、图片、Word文档等)进行处理,包括创建URL对象、转换格式和下载。

  // 预览文件
        preview: function(item) {
          var vm = this;
          if (!item.raw) {
            var itemBasicId = this.form.itemBasicId

            var url =ctx + '/aea/item/basic/getItemDocOrTemplateFile.do?itemBasicId='+itemBasicId+'&fileType=applyTableTemplate'
            
            axios({
            method: 'GET',
            headers: {  'Authorization': 'bearer '+localStorage.getItem("access_token") },
            url: url,
            originResponse: true,
            responseType: 'blob' // 更改responseType类型为 blob
          }).then( function(res) {
              vm.previewPdfAndPic(res.data)
          }).catch(function(err) {
            console.log(err)
          })
          }else{
          //  vm.openBlobFile(item)
          }
        },
       previewPdfAndPic: function (response) {
  
        var _fileName = '申请表模板.docx', fileType = 'pdf';

        if(response.headers['content-disposition']){
          var temp = response.headers['content-disposition'];
          _fileName = temp.split(';')[1].split('filename=')[1]; 

          fileType = _fileName.substring(_fileName.lastIndexOf('.')); 
          var fileName = _fileName.substring(0, _fileName.lastIndexOf('.')); // 文件名
        }
        console.log(fileName)
        console.log(fileType)
        try {

          if(fileType.toLocaleLowerCase === 'pdf'){
          // 转换pdf
          var blob = new Blob([response], { type: 'application/pdf' });
          var url = window.URL.createObjectURL(blob);
          var tempwindow=window.open(); // 先打开页面
          tempwindow.location= url
        }else if(['.png', '.jpg','.jpeg', '.gif'].indexOf(fileType.toLocaleLowerCase) !== -1){
            var imgBlob = new window.Blob([response], { type: 'image/png' })
            var url = window.URL.createObjectURL(blob);
            var tempwindow=window.open(); // 先打开页面
            tempwindow.location= url
        }else if(['.doc', '.docx'].indexOf(fileType.toLocaleLowerCase) !== -1){
          var downloadUrl = window.URL.createObjectURL(new Blob([response], { type: "application/octet-stream" }));
          var link = document.createElement('a');
          link.style.display = 'none';
          link.href = downloadUrl;
          link.download = decodeURI(_fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
          
        } catch (error) {

          var downloadUrl = window.URL.createObjectURL(new Blob([response], { type: "application/octet-stream" }));
          var link = document.createElement('a');
          link.style.display = 'none';
          link.href = downloadUrl;
          link.download = decodeURI(_fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
        
        
       }, 
       openBlobFile: function (item) {
          if(item.raw) {
            const tempFileType = item.name.substring(item.name.length - 4)
              if (['.pdf', '.PDF'].indexOf(tempFileType) !== -1) {
                state.ImgSrc = null
                state.PDFURL = window.URL.createObjectURL(props.fileRaw)
                openTips.close()
                return
              }
              if (['.png', '.jpg','.jpeg', '.gif'].indexOf(tempFileType) !== -1) {
                state.PDFURL = null
                const reader = new FileReader();
                reader.onload = (evt) => {
                  state.ImgSrc = evt.target.result
                };
                reader.readAsDataURL(props.fileRaw);
              }
          }
        },
    
我的代码在这啊 async getFileById() { this.loading = true; // 使用Element UI的Loading服务 const loadingInstance = this.$loading({ lock: true, text: '请求处理中,请稍候...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)', }); if (!this.originFileUUID) { const params = { knowledgeFileId: this.fileId, fileId: this.fileUUID, }; const result = await this.$http.previewContentNew(params); if (result) { if (result.headers['content-disposition']) { this.fileName = result.headers['content-disposition'].split(';')[1].split('filename=')[1]; this.fileType = this.fileName.substring(this.fileName.lastIndexOf('.'), this.fileName.length).toLowerCase(); this.fileUUID = result.headers['lawrobot-fileuuid']; } const office = decodeURIComponent(result.headers.office) ? decodeURIComponent(result.headers.office) : ''; const publishtime = result.headers.publishtime ? result.headers.publishtime : ''; const valid = this.filterField(Number.parseInt(result.headers.valid), this.validEnum, "value", "label"); const expirytime = result.headers.expirytime ? result.headers.expirytime : ''; const filePropertyDesc = decodeURIComponent(result.headers.filepropertydesc) ? decodeURIComponent(result.headers.filepropertydesc) : ''; this.showTitleTag = result.headers.showtitletag ? (result.headers.showtitletag === 'true') : false; const titleTag = `<div style="line-height:normal;letter-spacing: normal;border-bottom: 1px solid #f0f0f0;background: white;padding-left: 7px; padding-top: 35px;max-width: 1270px;min-height: 140px;margin:0 auto"> <div style="line-height:normal;letter-spacing: normal;float: left;border-right: 1px solid #f0f0f0;"> <div style="line-height:normal;letter-spacing: normal;"> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #9c9898;display: inline-block;width: 100px;padding-bottom: 5px;padding-left: 25px;">法律性质:<\/span> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #000000;display: inline-block;margin-left: 5px;font-weight: 500;padding-right: 35px;padding-bottom: 5px;">` + filePropertyDesc + `<\/span> <\/div> <div style="line-height:normal;letter-spacing: normal;"> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #9c9898;display: inline-block;width: 100px;padding-bottom: 5px;padding-left: 25px;">公布日期:<\/span> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #000000;display: inline-block;margin-left: 5px;font-weight: 500;padding-right: 35px;padding-bottom: 5px;">` + publishtime + `<\/span> <\/div> <div style="line-height:normal;letter-spacing: normal;"> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #9c9898;display: inline-block;width: 100px;padding-bottom: 5px;padding-left: 25px;">实施日期:<\/span> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #000000;display: inline-block;margin-left: 5px;font-weight: 500;padding-right: 35px;padding-bottom: 5px;">` + expirytime + `<\/span> <\/div> <\/div> <div style="line-height:normal;letter-spacing: normal;float: left;margin: 0px 15px;min-width: 300px;"> <div style="line-height:normal;letter-spacing: normal;"> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #9c9898;display: inline-block;width: 80px;padding-bottom: 5px;padding-left: 25px;">时效性:<\/span> <span style="line-height:normal;letter-spacing: normal;font-size: 20px !important;text-align: left;color: #000000;display: inline-block;margin-left: 20px;font-weight: 500;padding-right: 10px;padding-bottom: 5px;">` + valid + `<\/span> <\/div> <div style="display: flex; align-items: flex-start; line-height: normal; letter-spacing: normal;"> <span style="line-height: normal; letter-spacing: normal; font-size: 20px !important; text-align: left; color: #9c9898; width: 100px; padding-bottom: 5px; padding-left: 25px;">制定机关:<\/span> <span style="line-height: normal; letter-spacing: normal; font-size: 20px !important; text-align: left; color: #000000; max-width: 620px; margin-left: 1px; font-weight: 500; padding-right: 10px; padding-bottom: 5px; word-break: break-all; text-overflow: ellipsis; display: inline-block;">` + office + `<\/span> <\/div> <\/div> <\/div>`; // 创建固定div的HTML模板 const headerHtml = `<div style="line-height:normal;letter-spacing: normal;position: sticky !important; top: 0px;z-index:10000;background: white; margin:0 auto;max-width: 1277px;"> <p style="line-height:normal;letter-spacing: normal;padding-top: 20px;padding-bottom:8px;text-align:left;font-size: 32px !important;min-height: 70px;color: #000000;font-weight: 500;border-bottom: 1px solid #f0f0f0;padding-left: 25px;">` + decodeURIComponent(this.fileName).split('.').slice(0, -1).join('.') + `<\/p> <\/div>`; const content = result.data // 1. 去掉body::before的content属性 .replace(/body::before\s*\{[^}]*?\bcontent\s*:\s*['"][^'"]*?['"]\s*;/g, match => match.replace(/\bcontent\s*:\s*['"][^'"]*?['"]\s*;?/, '')) // 2. 修改body标签的padding样式 .replace(/<body[^>]*?style\s*=\s*["'][^"']*?\bpadding\s*:\s*20px\s+0[^"']*?["'][^>]*?>/g, match => match.replace(/\bpadding\s*:\s*20px\s+0\s*;?/, 'padding: 0;')) // 3. 修改.container的width样式 .replace(/\.container\s*\{[^}]*?\bwidth\s*:\s*1276px\s*;[^}]*?\}/g, match => match.replace(/\bwidth\s*:\s*1276px\s*;?/, 'width: 1240px;')) // 4. 修改.container的margin样式 .replace(/\.container\s*\{[^}]*?\bmargin\s*:\s*20px\s+auto\s*;[^}]*?\}/g, match => match.replace(/\bmargin\s*:\s*20px\s+auto\s*;?/, 'margin: 0 auto;')) // 4. 新增:修改.pdf-page的margin样式 .replace(/\.pdf-page\s*\{[^}]*?\bmargin\s*:\s*20px\s+auto[^}]*?\}/g, match => match.replace(/\bmargin\s*:\s*20px\s+auto\s*;?/, 'margin: 0 auto;')); let tagHtml; if (this.showTitleTag){ tagHtml = `<!DOCTYPE html> <html lang="zh-CN" style="background-color: #f0f0f0 !important;"> <head><meta charset="UTF-8"><\/head> <body><div style="position: relative;">` + headerHtml + `<div style="margin-top: -33px">` + titleTag; } else { tagHtml = `<!DOCTYPE html> <html lang="zh-CN" style="background-color: #f0f0f0 !important;"> <head><meta charset="UTF-8"><\/head> <body><div style="position: relative;">` + headerHtml + `<div style="margin-top: -33px">`; } this.$refs.htmlIframe.srcdoc = tagHtml + `<iframe id="nestedHtml" style="width: 100%; border: none; margin: 0 auto !important;" srcdoc='` + content + `'><\/iframe> <\/div> <\/div> <script> window.jumpToAnchor = function(hash) { const iframe = document.getElementById('nestedHtml'); // 确保iframe内容已加载 if (!iframe.contentDocument) { setTimeout(() => processAnchorJump(hash), 50); return; } const iframeDoc = iframe.contentDocument; const element = iframeDoc.getElementById(hash); if (!element) { console.log('未找到锚点元素:', hash); return; } // 先将页面滚动到顶部(还原到初始位置) window.scrollTo(0, 0); // 等待滚动完成后再计算位置 setTimeout(() => { // 使用getBoundingClientRect获取元素位置 const elementRect = element.getBoundingClientRect(); const iframeRect = iframe.getBoundingClientRect(); // 计算总偏移量(减去上方固定div的高度) const topOffset = iframeRect.top + elementRect.top - 110; console.log("总偏移量:", topOffset); // 执行滚动到目标位置 window.scrollTo({ top: topOffset, behavior: 'smooth' }); }, 100); }; // 动态调整iframe高度以适应内容 document.getElementById('nestedHtml').addEventListener('load', function() { const iframe = this; const iframeDoc = iframe.contentDocument || iframe.contentWindow.document; const contentHeight = iframeDoc.body.scrollHeight; // 设置iframe高度为内容高度 iframe.style.height = contentHeight + 'px'; }); <\/script> <\/body> <\/html>`; } else { this.$message.error("暂无可预览文件"); } } else { const params = { fileId: this.originFileUUID, }; const result = await this.$http.previewFileNew(params); if (result.data) { const type = this.getFileMimeType(this.fileType); const blob = new Blob([result.data], { type: type + ';charset=utf-8', name: this.fileName, }); this.fileUrl = window.URL.createObjectURL(blob); } else { this.$message.error("暂无可预览文件"); } } this.loading = false; loadingInstance.close(); // 设置标题 document.title = this.fileName ? decodeURIComponent(this.fileName) : document.title; }, 目前圈复杂度为12,需要降低到10以下,但是不能改变代码本身逻辑
10-24
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

春风得意之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值