原生Ajax发送文件流

2022-04-12  本文已影响0人  王二麻子88
/**
* @param url
* @param param 参数对象(包含文件):param.file(el-upload)/param.target.files[0](input[file])
* @param cb 发送成功的回调函数
*/
export function requestImport(url, param, cb, queryStr) {
    var file
    // 加上param.raw,有的组件取回的文件对象,属性值放在raw而非file里
    if (param.file || param.raw) {
        file = param.file || param.raw
    } else {
        file = param.target.files[0]
    }
    var fullUrl = url + `?token=${Cookies.get('token')}`
    // 设置全路径
    if (fullUrl.indexOf('http://') !== 0 && fullUrl.indexOf('https://') !== 0) {
        fullUrl = process.env.VUE_APP_BASE_API + fullUrl
    }

    var xhr = new XMLHttpRequest()
    xhr.open('POST', fullUrl + (queryStr || ''))
    xhr.setRequestHeader('Authorization', Cookies.get('token'))
    xhr.overrideMimeType('application/octet-stream')
    var chunks = file.slice(0, file.size)
    this.$utils.getFileBinary(chunks, function (binary) {
        if (xhr.sendAsBinary) {
            xhr.sendAsBinary(binary)
        } else {
            xhr.send(binary)
        }
    })

    xhr.onreadystatechange = function (e) {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                var resp = JSON.parse(xhr.responseText)
                if (typeof cb === 'function') {
                    cb.call(this, resp)
                }
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读