All files / src/components/u-uploader.vue ajax.js

0% Statements 0/44
0% Branches 0/34
0% Functions 0/8
0% Lines 0/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87                                                                                                                                                                             
function getError(url, options, xhr) {
    let msg;
    if (xhr.response) {
        msg = `${xhr.response.error || xhr.response}`;
    } else if (xhr.responseText) {
        msg = `${xhr.responseText}`;
    } else {
        msg = `Fail to post ${url} ${xhr.status}`;
    }
 
    const err = {
        msg,
        status: xhr.status,
        method: 'post',
        url
     };
    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 upload(options) {
    if (typeof XMLHttpRequest === 'undefined')
        return;
 
    const xhr = new XMLHttpRequest();
    const url = options.url;
 
    if (xhr.upload) {
        xhr.upload.onprogress = function onprogress(e) {
            if (e.total > 0) {
                e.percent = e.loaded / e.total * 100;
            }
            options.onProgress(e);
        };
    }
 
    const formData = new FormData();
 
    if (options.data) {
        Object.keys(options.data).forEach((key) => {
            formData.append(key, options.data[key]);
        });
    }
 
    const files = options.file.length ? Array.from(options.file) : [options.file];
    files.forEach((file) => formData.append(options.name, file, file.name));
 
    xhr.onerror = function onerror(e) {
        options.onError(e);
    };
 
    xhr.onload = function onload() {
        if (xhr.status < 200 || xhr.status >= 300) {
            return options.onError(getError(url, options, xhr));
        }
 
        options.onSuccess(getBody(xhr));
    };
 
    xhr.open('post', url, true);
 
    if (options.withCredentials && 'withCredentials' in xhr) {
        xhr.withCredentials = true;
    }
 
    const headers = options.headers || {};
 
    for (const key in headers) {
        if (headers.hasOwnProperty(key) && headers[key] !== null) {
            xhr.setRequestHeader(key, headers[key]);
        }
    }
    xhr.send(formData);
    return xhr;
}