Vue implements download function with iframe

Before downloading, you must first obtain the url of the file download address. If you have obtained the url before executing the download method, you can write it to the downLoad method by passing parameters. If you have not, you can call it in the downLoad method. Interface to get url.

1. Single download

downLoad (url) {
    const iframe = document.createElement("iframe");
    iframe.src = url;
    iframe.style.display = "none"; // 防止影响页面
    iframe.style.height = 0; // 防止影响页面
    document.body.appendChild(iframe); // 必写,iframe挂在到dom树上才会发请求
    // 定时删除节点
    setTimeout(() => {
       document.body.removeChild(iframe);
    }, 2000);
}

 2. Batch download

Similar to a single download, batches only need to traverse to get the url that needs to be downloaded, and create iframe nodes in a loop.

downLoad () {
    // 这里的 detail 是一个已知的对象
    // picList  picList 是两个数组,里面是一个个对象,每个对象里有一个我们下载要用的downUrl
    // 通过扩展运算符(...)展开后,data的形式就是 [{...},{..},{...},...]
      const data = [
        ...this.detail.picList,
        ...this.detail.videoList
      ];
      for (let i = 0; i < data.length; i++) {
        const url = data[i].downUrl;
        const iframe= document.createElement('iframe');
        iframe.src = url;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
        setTimeout(() => {
          document.body.removeChild(iframe);
        }, 2000);
}

The array data stores all the file objects that need to be downloaded. By traversing the data, each time you get the url in the object, you can perform the same operation as a single download.

(Remarks: The urls mentioned here are all obtained from the backend, and the functions can be realized, but I tried to click to download the pictures or file links I found on the Internet, but there is no response. I don’t know the reason. .)

Guess you like

Origin blog.csdn.net/weixin_44427784/article/details/120436907