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