簡體   English   中英

如何使用JS fetch重寫角度ng-file-upload Upload.upload?

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

我需要使用來自react native app的fetch()將文件上傳到服務器

我在Angular中使用以下代碼使用ng-file-upload

在此函數文件變量中附加了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);
    }

我嘗試使用fetch()執行以下操作,但它無法正常工作:文件已添加到服務器,但附件和其他字段未保存在那里。 這是我試過的代碼:

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))
}

這里似乎混合了兩種Content-Types

  • multipart/form-data用於發送在文件的二進制內容file
  • application/json用於在body發送一些JSON數據

由於HTTP請求僅支持具有一個Content-Type編碼的一個主體,因此我們必須將所有這些統一為multipart/form-data 以下示例使用變量formData將(二進制)文件數據與任意JSON數據組合在一起。

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))
}

HTTP請求主體的有效負載將如下所示:

------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--

參考文獻:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM