Vue and js click to download files in pdf, word, png, jpg and other formats, to solve the problem of opening the preview when clicking to download pdf

Foreword:

      In our project, it is very convenient to download png, jpg files, dynamically generate an a tag, assign a path to it, and click dynamically to achieve this function, but pdf, word and other types of files are not available because of browsing The browser does not allow us to click to download directly, but click to preview, we share the respective methods here.

table of Contents:

 1. How to download png, jpg and other common problems

Method 1: (jpg, png, etc.)

Method 2: (word(docx) excel(xlsx) ppt jpg png, etc.)

2. How to download pdf ()

***Before talking about the specific method, first solve a problem, which is to use the following method: Click to download the pdf but open the preview problem (mock.js, if mock.js is used in the page, this problem will definitely occur, because we The request to open the page was intercepted, the solution is to remove the mock introduced in the page), the following is the mock introduced in my project, which must be commented to solve this problem

Method one: pdf

Method 2: pdf, xlsx and other formats


 1. How to download png, jpg and other common problems

Method 1: (jpg, png, etc.)

const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url  //(放你的路径)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

Method 2: (word(docx) excel(xlsx) ppt jpg png, etc.)

/**
 *下载或导出文件
 * @param blob  :返回数据的blob对象
 * @param tagFileName  :下载后文件名标记
 * @param fileType  :文件类 word(docx) excel(xlsx) ppt等
 */
const saveFileToBlob = (blob, tagFileName, fileType) => {
  // if (fileType) {
  //   console.warn('未传入文件类型,例如文件类 word(docx) excel(xlsx) ppt jpg png等')
  // }
  // if (isBlob(blob)) {
  var downloadElement = document.createElement('a')
  let href = window.URL.createObjectURL(blob) //创建下载的链接
  downloadElement.href = href
  downloadElement.download = tagFileName + '.' + fileType //下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() //点击下载
  document.body.removeChild(downloadElement) //下载完成移除元素
  window.URL.revokeObjectURL(href) //释放掉blob对象
  // } else {
  //   console.warn('不是blob对象类型的参数,可选择saveFileToBase64(Base64对象,文件类型)或saveFileToLink(文件链接,文件名,文件类型,进度回调方法)')
  // }
}


2. How to download pdf ()

***Before talking about the specific method, first solve a problem, which is to use the following method: Click to download the pdf but open the preview problem (mock.js, if mock.js is used in the page, this problem will definitely occur, because we The request to open the page was intercepted, the solution is to remove the mock introduced in the page ), the following is the mock introduced in my project , which must be commented to solve this problem

Method one: pdf

调用:
let  src = '你的pdf路径'
downloadFile(src,'333')//地址,你的文件名
    /**
     * 下载文件,支持pdf,word等格式
     * */
    const downloadFile = (data, fileName ) => {
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', fileName + '.pdf');
      document.body.appendChild(link);
      link.click();
    }

Method 2: pdf, xlsx and other formats

//调用
saveFileToLink(url,'555','pdf') //地址,文件名,文件类型
    /**
     * 文件链接转文件流下载--主要针对pdf 解决谷歌浏览器a标签下载pdf直接打开的问题
     * @param url  :文件链接
     * @param fileName  :文件名;
     * @param type  :文件类型;
     * @param fn  :进度回调方法;
     */
    const saveFileToLink = (url, fileName, type, fn) => {
      if (!CheckUrl(url)) {
        throw new Error('传入参数不合法,不是标准的文件链接')
      } else {
        var xhr = new XMLHttpRequest()
        // url = url.includes('https:') ? url.replace('https:', '') : url.replace('http:', '')//资源路径动态获取请求的方式HTTPS或HTTP
        // console.log(url)
        xhr.open('get', url, true)
        xhr.setRequestHeader('Content-Type', `application/${type}`)
        xhr.setRequestHeader('If-Modified-Since', '0') //解决缓存问题,每次请求都去请求服务器获取最新数据
        xhr.responseType = 'blob'
        xhr.onprogress = function(e) { //文件下载进度
          if (fn && typeof fn === 'function') {
            fn(e)//监听文件下载进度;
          }
        },
          xhr.onload = function() {
            if (this.status == 200) {
              //接受二进制文件流
              var blob = this.response
              saveFileToBlob(blob, fileName, type)
            }
          },
          xhr.send()
      }
    }
    /**
     *下载或导出文件
     * @param blob  :返回数据的blob对象
     * @param tagFileName  :下载后文件名标记
     * @param fileType  :文件类 word(docx) excel(xlsx) ppt等
     */
    const saveFileToBlob = (blob, tagFileName, fileType) => {
      // if (fileType) {
      //   console.warn('未传入文件类型,例如文件类 word(docx) excel(xlsx) ppt jpg png等')
      // }
      // if (isBlob(blob)) {
      var downloadElement = document.createElement('a')
      let href = window.URL.createObjectURL(blob) //创建下载的链接
      downloadElement.href = href
      downloadElement.download = tagFileName + '.' + fileType //下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放掉blob对象
      // } else {
      //   console.warn('不是blob对象类型的参数,可选择saveFileToBase64(Base64对象,文件类型)或saveFileToLink(文件链接,文件名,文件类型,进度回调方法)')
      // }
    }
    /**
     * 校验是否url链接
     * @param url  :url链接
     * @returns {Bool}:是否url链接
     */
    const CheckUrl = (url) => {
      let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/
      return reg.test(url)
    }

It's over here!

Guess you like

Origin blog.csdn.net/qq_41619796/article/details/114523103