前端下载网页文件或图片

118 阅读1分钟
  • 技术栈:vue2
  • 需求:点击按钮下载文件或图片(绝对路径)
              <el-table-column fixed="right" label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-download" @click="onDownloadDriver(scope.row)">
                    下载
                  </el-button>
                </template>
              </el-table-column>
  onDownloadDriver(row) {
      let link = document.createElement("a");
      let url = row.attachment;
      // 这里是将url转成blob地址,
      console.log('url', url);
      fetch(url)
        .then((res) => res.blob())
        .then((blob) => {
          // 将链接地址字符内容转变成blob地址
          link.href = URL.createObjectURL(blob);
          console.log(link.href);
          link.download = ""; //为空使用下载名称
          document.body.appendChild(link);
          link.click();
          link.remove()
        });
    },