vue 单个文件下载重命名和多个文件下载成压缩包重命名 总结

1.单个文件下载重命名

//下载单个改名 url--下载地址 name -- 下载名字
export function filterDownLoad(url, name) {
    fetch(url).then(_ => _.blob()).then(_ => {
        const link = document.createElement('a');
        link.href = URL.createObjectURL(_);
        link.setAttribute('download', name); // 自定义文件名
        link.click();
    })
}

2.多个文件下载重命名

/*
 首先得下载依赖:
    1. npm i jszip -S
    2. npm i file-saver -S
*/
import JSZip from 'jszip';
import FileSaver from 'file-saver';
//下载多个 list下载文件列表 nameDownload 下载过后zip名字
export function downLoadMore(list, nameDownload) {
    const zip = new JSZip()
    const promisesList = []
    for (let i = 0; i < list.length; i++) {
        const file = list[i]
        // file.downloadPath  文件地址  
        const promise = getFileArrayBuffer(file.downloadPath).then(
            (data) => {
                // 下载文件, 并存成ArrayBuffer对象(blob)   file.fileName 每个文件文件名字
                zip.file(file.fileName, data, { binary: true }) // 逐个添加文件
            })
        promisesList.push(promise)
    }
    Promise.all(promisesList).then(() => {
        zip.generateAsync({ type: 'blob' }).then((content) => {
            // 生成二进制流 time
            FileSaver.saveAs(content, nameDownload + '.zip') // 利用file-saver保存文件  自定义文件名
        })
    })
};
// 通过请求获取文件blob格式
function getFileArrayBuffer(url) {
    return new Promise((resolve, reject) => {
        const xmlhttp = new XMLHttpRequest()
        xmlhttp.open('GET', url, true)
        xmlhttp.responseType = 'blob'
        xmlhttp.onload = function () {
            if (this.status == 200) {
                resolve(this.response)
            } else {
                reject(this.status)
            }
        }
        xmlhttp.send()
    })
}

猜你喜欢

转载自blog.csdn.net/xiao_ju_ju/article/details/134315917