2021-05-09 10:46:11 +08:00
|
|
|
import { hasOwn } from '@vue/shared'
|
2020-09-27 12:10:36 +08:00
|
|
|
import type {
|
|
|
|
ElUploadProgressEvent,
|
|
|
|
ElUploadRequestOptions,
|
|
|
|
ElUploadAjaxError,
|
2020-11-26 23:09:31 +08:00
|
|
|
} from './upload.type'
|
2020-09-27 12:10:36 +08:00
|
|
|
|
2021-09-04 19:29:28 +08:00
|
|
|
function getError(
|
|
|
|
action: string,
|
|
|
|
option: ElUploadRequestOptions,
|
|
|
|
xhr: XMLHttpRequest
|
|
|
|
) {
|
2020-09-27 12:10:36 +08:00
|
|
|
let msg: string
|
|
|
|
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) as ElUploadAjaxError
|
|
|
|
err.status = xhr.status
|
|
|
|
err.method = 'post'
|
|
|
|
err.url = action
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
function getBody(xhr: XMLHttpRequest): XMLHttpRequestResponseType {
|
|
|
|
const text = xhr.responseText || xhr.response
|
|
|
|
if (!text) {
|
|
|
|
return text
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
return JSON.parse(text)
|
|
|
|
} catch (e) {
|
|
|
|
return text
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function upload(option: ElUploadRequestOptions) {
|
|
|
|
if (typeof XMLHttpRequest === 'undefined') {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
const xhr = new XMLHttpRequest()
|
|
|
|
const action = option.action
|
|
|
|
|
|
|
|
if (xhr.upload) {
|
|
|
|
xhr.upload.onprogress = function progress(e) {
|
|
|
|
if (e.total > 0) {
|
2021-09-04 19:29:28 +08:00
|
|
|
;(e as ElUploadProgressEvent).percent = (e.loaded / e.total) * 100
|
2020-09-27 12:10:36 +08:00
|
|
|
}
|
|
|
|
option.onProgress(e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const formData = new FormData()
|
|
|
|
|
|
|
|
if (option.data) {
|
2021-09-04 19:29:28 +08:00
|
|
|
Object.keys(option.data).forEach((key) => {
|
2020-09-27 12:10:36 +08:00
|
|
|
formData.append(key, option.data[key])
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
formData.append(option.filename, option.file, option.file.name)
|
|
|
|
|
|
|
|
xhr.onerror = function error() {
|
|
|
|
option.onError(getError(action, option, xhr))
|
|
|
|
}
|
|
|
|
|
|
|
|
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) {
|
2021-05-09 10:46:11 +08:00
|
|
|
if (hasOwn(headers, item) && headers[item] !== null) {
|
2020-09-27 12:10:36 +08:00
|
|
|
xhr.setRequestHeader(item, headers[item])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
xhr.send(formData)
|
|
|
|
return xhr
|
|
|
|
}
|