UNPKG

magiccube-vue3

Version:

vue3-js版组件库

95 lines (78 loc) 2.22 kB
function getError(action, option, xhr) { let msg if (xhr.response) { msg = `${xhr.response.error || xhr.response}` } else if (xhr.responseText) { msg = `${xhr.responseText}` } else { msg = `fail to post ${action} ${xhr.status}` } const err = new Error(msg) err.status = xhr.status err.method = 'post' err.url = action return err } function getBody(xhr) { const text = xhr.responseText || xhr.response if (!text) { return text } try { return JSON.parse(text) } catch (e) { return text } } export default function (option) { if (typeof XMLHttpRequest === 'undefined') { return } const xhr = new XMLHttpRequest() // new xhr const action = option.action if (xhr.upload && option.onProgress) { xhr.upload.onprogress = function progress(e) { if (e.total > 0) { e.percent = e.loaded / e.total * 100 } option.onProgress(e) } } const formData = new FormData() //通过formData上传 if (option.extraParams) { Object.keys(option.extraParams).forEach(key => { formData.append(key, option.extraParams[key]) }) } if(option.multi){ // 主要针对58的图片批量上传 option.file.forEach(file => formData.append('file', file)) } else { formData.append('file', option.file) } if(option.onError){ xhr.onerror = function error(e) { option.onError(e) } } if(option.onSuccess){ xhr.onload = function onload() { if (xhr.status < 200 || xhr.status >= 300) { return option.onError(getError(action, option, xhr)) } option.onSuccess(getBody(xhr)) } } xhr.open('post', action, true) if (option.withCredentials && 'withCredentials' in xhr) { xhr.withCredentials = true } const headers = option.headers || {} for (const item in headers) { if (Object.prototype.hasOwnProperty.call(headers, item) && headers[item] !== null) { xhr.setRequestHeader(item, headers[item]) } } xhr.send(formData) return xhr }