a标签下载文件,图片,txt文件

 

    urlToBlob(swiperItem) {
      // let file_url =
      //   'http://obdataplatform-test.oss-cn-shenzhen.aliyuncs.com/2020_07_10/391f56b9-f4bc-408b-868b-31ea0f8b1b47.hex'
      return new Promise(resolve => {
        let file_url =
          "https://rds.wm-motor.cn/file-proxy/?url=" +
          encodeURI(swiperItem.path);
        let xhr = new XMLHttpRequest();
        xhr.open("get", file_url, true);
        xhr.responseType = "blob";
        let _that = this;
        xhr.onload = function() {
          if (this.status == 200) {
            const reader = new FileReader();
            reader.onload = function() {
              _that.txtContent = reader.result;
              resolve(reader.result);
            };
            reader.readAsText(this.response);
          }
        };
        xhr.send();
      });
    },

 

  

使用a标签下载文件的时候设置下载文件的文件名

给a标签加一个download属性    可以设置下载下来的文件的文件名    

注意:下载的地址域名和访问网站的域名是同源  否则设置无效

    // 下载图片
    downloadIamge(swiperItem) {//下载图片地址和图片名
      console.log('swiperItem', swiperItem)
      // let src = 'http://pic.c-ctrip.com/VacationH5Pic/mice/wechat/ewm01.png';
      let src = 'https://rds.wm-motor.cn/file-proxy/?url=' + encodeURI(swiperItem.path)
        var canvas = document.createElement('canvas');
        var img = document.createElement('img');
        img.onload = function(e) {
            canvas.width = img.width;
            canvas.height = img.height;
            var context = canvas.getContext('2d');
            context.drawImage(img, 0, 0, img.width, img.height);
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
            canvas.toBlob((blob)=>{
                let link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = swiperItem.docName; 
                link.click();  
            }, "image/jpeg");
        }
        img.setAttribute("crossOrigin",'Anonymous');
        img.src = src;
    },
  ,

  

 

 // 下载文件,区分txt文件
    handleDownload(swiperItem){
    // txt文件
if(swiperItem.docName.split(".")[1] == 'txt'){ this.urlToBlob(swiperItem).then(() => { let url = new Blob(['\ufeff' + this.txtContent], {type: 'text/tet,charset=UTF-8'}); swiperItem.path = URL.createObjectURL(url); const a = document.createElement('a') a.setAttribute('download', swiperItem.docName) a.setAttribute('target', '_blank') a.setAttribute('href', swiperItem.path) a.click() }) // openDownloadDialog(blob, `${fileName}.csv`); }else {
    //其他文件 const a
= document.createElement('a') a.setAttribute('target', '_blank') let path = 'https://rds.wm-motor.cn/file-proxy/?url=' + encodeURI(swiperItem.path) a.setAttribute('href', path) a.setAttribute('download', swiperItem.docName) a.click() } }

 

posted @ 2021-02-04 16:10  sinceForever  阅读(689)  评论(0编辑  收藏  举报