关于前端文件预览后台返回Bolb类型

1,298 阅读1分钟

今天遇到个问题,预览文件的时候(pdf或者docx),当点击预览,得到下面数据,如果是pdf格式,后缀就是pdf, docx是word文档

image.png

这里我先自己学习下Blob类型

 var str = "123";
    // Blob第一个参数数数组,第二个参数数类型配置type
    // 下面这个是文本type类型,更多type类型可以看下面链接
    const blob = new Blob([str], { type: "text / palin" });
    console.log(blob);
    //  blob.text()是实例对象一个方法,是一个promise,可以在成功的回调拿到上述文本的值
    blob.text().then((res) => {
      console.log(res);  123
    });

image.png type类型介绍:blog.csdn.net/weixin_4355…

文件下载

利用a标签 上的dowload属性,但是href如果不是同源地址,下载不了

<a href="" download=""></a>

利用Blob和a标签实现下载的例子

 <body>
    <a id="btn">下载</a>
    <script>
      var str = `<div><p>我是下载的文件</p></div>`;
      const blob = new Blob([str], { type: "text/html" });
      btn.onclick = function (e) {
        this.setAttribute("download", "5-9"); // 属性值就是下载的文件名
        this.href = URL.createObjectURL(blob); //只能将blob变成url,生成的url是同源的
      };
    </script>
  </body>

利用input实现本地文件下载

 <body>
    <input type="file" id="input" />
    <script>
      input.onchange = function (e) {
        console.log(e);
        
        console.log(file);

        let a = document.createElement("a");
        a.setAttribute("download", "mybaidu.html");
        a.href = URL.createObjectURL(file);
        a.click();
      };
    </script>
  </body>

利用input实现本地图片上传并显示

<body>
    <input type="file" id="input" />
    <script>
      input.onchange = function (e) {
        var file = e.target.files[0];
        const img = new Image();
        img.src = URL.createObjectURL(file);
        document.body.appendChild(img);
      };
    </script>
  </body> 

这里写下项目中用到的将文件流转化为url

// 获取文件二进制数据并转换临时路径
export const getFileBlob = (data) => {
  return server({
    url: " ", 接口地址
    method: "get",
    params: data,
    responseType: "blob",
  }).then((res) => {
    let metaType = "application/pdf";
    if (data.type == "docx") {
      metaType =
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
    }
    let fileURL = null;
    let blob = new Blob([res], { type: metaType });
    if (window.createObjectURL != undefined) {
      // basic
      fileURL = window.createObjectURL(blob);
    } else if (window.webkitURL != undefined) {
      // webkit or chrome
      try {
        fileURL = window.webkitURL.createObjectURL(blob);
      } catch (error) {
        console.log(error);
      }
    } else if (window.URL != undefined) {
      // mozilla(firefox)
      try {
        fileURL = window.URL.createObjectURL(blob);
      } catch (error) {
        console.log(error);
      }
    }

    return fileURL;
  });
};

如果后台返回的是url,文件下载

export const downloadFile = (url, param = {}) => {
  if (!url) return
  const queryStr = encodeURI(queryStringify(param))
  url += `${url.includes('?') ? (url[url.length - 1] === '&' ? '' : '&') : '?'}${queryStr}`

  const { apiBaseUrl } = require('@/config/baseUrl')
  const a = document.createElement('a')
  a.style.display = 'none'
  // a.href = 'http://192.168.1.36:8882/api/upload/downloadFile?fileUrl=hydq-mall-restfulapi/src/main/resources/static/bid/dept/dept/20220126174154-双击看看.bat'
  a.href = apiBaseUrl + url
  a.target = '_blank'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}