In many cases, the front end completes the file download

Requirement 1

The user requests to download the uploaded file immediately after uploading the file. Currently, the uploaded file is only uploaded locally and not uploaded to the service.

/**
 * 前端将文件上传到本地后,马上下载上传到本地的文件
 * file 上传到本地的文件
 */
export function downloadImmediately(file){
    // 模拟点击点击事件
    const a = document.createElement('a')
    // 在浏览器打开
    const URL = window.URL || window.webkitURL
    // 根据解析后的blob对象创建URL对象
    const href = URL.createObjectURL(file)
    // 下载链接
    a.href = href
    // 设置下载文件的文件名
    a.download = this.file.name
    // 将下载的节点进行插入
    document.body.appendChild(a)
    // 点击下载
    a.click()
    // 下载完成后清楚数据
    document.body.removeChild(a)
    window.URL.revokeObjectURL(href)
}

Requirement 2

The user downloads a file or picture that is already on the server, and the backend returns it through the file stream, downloading the stream file returned by the backend

1-1. Save the required data locally when intercepting the response

const service = axios.create({
    Headers: {
        "X-Requested-With": "XMLHttpRequest" // 标识时ajax请求
    },
    timeout: 60000
})
service.interceptors.response.use(res => {
    const code = res.data.mesgCode
    if(code === 200){
        if(res.Headers["content-disposition"]){
            const contentDisposition = decodeURI(res.Headers["content-disposition"])
            if(contentDisposition.indexOf("fileName") !== -1){
                sessionStorage.setItem("contentDisposition", contentDisposition)
                sessionStorage.setItem("contentType", res.Headers["content-type"])
            }
        }
    }
})

1-2. Obtain the file information to be downloaded

/**
 * 获取文件中的信息
 */
export function findFileName(){
    // 以下sessionStorage所使用的数据都是拦截相应信息,存储的相应头中的数据
    // 在返回先拦截返回信息,取出响应头中的信息存在sessionStorage,在此处从sessionStorage中获取
    let file = sessionStorage.getItem('contentDisposition')
    // contentDisposition含有多项信息,中间时用空格分隔
    const fileArr = file.split(' ')
    let fileName = ''
    fileArr.forEach(item => {
        let index = item.indexOf('filename')
        if(index !== -1){
            let fileNameStr = ''
            for(let i = 0; i < item.length; i++){
                fileNameStr += item[i].replace('"', '')
            }
            fileName = fileNameStr.split('=')[1]
            return
        }
    })
    const contentType = sessionStorage.getItem('contentType')
    // 数据处理完成后清除存在sessionStorage下载所需要的数据
    sessionStorage.removeItem('contentDisposition')
    sessionStorage.removeItem('contentType')
    // 返回文件名、文件格式
    return {
        name: fileName.split('.')[0],
        type: contentType
    }
}

2. Summarize file information and file flow for download

/**
 * 下载后端返回的流文件
 * res 后端返回的文件流
 * fileName 下载文件的文件名
 * type 文件格式
 */
export function download(res, fileName, type){
    // 创建一个blob对象
    const blob = new Blob([res], {
        type
    })
    // 以下内容与上传到本地的图片下载一致
    const a = document.createElement('a')
    const URL = window.URL || window.webkitURL
    // 根据解析后的blob对象创建URL对象
    const href = URL.createObjectURL(blob)
    a.href = href
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(href)
}

There is another method that is not used much, but it is very convenient. The backend directly returns a download link, and the download can be completed through the open method.

window.open(url)

Guess you like

Origin blog.csdn.net/m0_46114541/article/details/130739803