简体   繁体   中英

How to rewrite angular ng-file-upload Upload.upload with JS fetch?

I need to upload file to server using fetch() from react native app

I have the following code in Angular which uses ng-file-upload :

in this function file variable is attached FormData

    function addDocumentToMessage(messageId, file) {

        data.filepath = file;
        data.name = file.name;

        return Upload.upload({
                url: BackendUrl + "/messages/" + messageId + "/attachments/",
                file: file,
                data: data
            })
            .then(responseHandler)
            .catch(errorHandler);
    }

I tried to do following using fetch() but it doesn't work correctly: file is added to server but attachment and other fields are not saved there. Here is the code I tried:

document = { formData, name }

export const addDocumentToMessage = (token, logId, document) => {
    const file = document.formData
    const data = { filepath: file, name: document.name }

    fetch(`${API_URL}/messages/${logId}/attachments/`, {
        method: 'POST',
        headers: { 'Authorization': `token ${token}`, 'Content-Type': 'multipart/form-data', Accept: 'application/json' },
        body: JSON.stringify({ file: file, data: data })
    })
        .then(response => console.log(response.data))
        .catch(error => console.log(error.message))
}

It seems that two Content-Types were mixed here:

  • multipart/form-data for sending binary content of the file in file
  • application/json for sending the some JSON data in body

Since HTTP requests only support one body having one Content-Type encoding we have to unify all of that to be multipart/form-data . The following example is using variable formData to combine (binary) file data with arbitrary JSON data.

export const addDocumentToMessage = (token, logId, document) => {

    // commented these lines since I wanted to be more specific
    // concerning the origin and types of data
    // ---
    // const file = document.formData
    // const data = { filepath: file, name: document.name }

    const fileField = document.querySelector("input[type='file']");
    let formData = new FormData();

    formData.append('file', fileField.files[0]);
    formData.append('name'. fileField.files[0].name);
    formData.append('arbitrary', JSON.stringify({hello: 'world'}));

    fetch(`${API_URL}/messages/${logId}/attachments/`, {
        method: 'POST',
        headers: {
            'Authorization': `token ${token}`,
            'Accept': 'application/json'
            // 'Content-Type': 'multipart/form-data',
        },
        body: formData
    })
        .then(response => console.log(response.data))
        .catch(error => console.log(error.message))
}

The payload of HTTP request body would then look like this:

------WebKitFormBoundarypRlCB48zYzqAdHb8
Content-Disposition: form-data; name="file"; filename="some-image-file.png"
Content-Type: image/png

... (binary data) ...
------WebKitFormBoundarypRlCB48zYzqAdHb8
Content-Disposition: form-data; name="name"

some-image-file.png
------WebKitFormBoundarypRlCB48zYzqAdHb8
Content-Disposition: form-data; name="arbitrary"

{"hello":"world"}
------WebKitFormBoundarypRlCB48zYzqAdHb8--

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM