【问题标题】:How to submit a file using Fetch API from an input element如何使用 Fetch API 从输入元素提交文件
【发布时间】:2018-11-13 15:30:08
【问题描述】:

用户将选择一个图像,然后我想将此图像发送到后端。

图片的发送是在body中处理的,比如我在postman上测试成功,我选择body->binary直接上传图片。

我想使用 javascript fetch api 复制此请求。

提交

 <input id="front" class="inputfile" type="file" onchange="frontChange(this)">

 async function frontChange(file) {
        this.frontInput = file
 }

 async function done() {

    const res = await this.submitDocument(this.frontInput.files[0]);
    console.log(res); 

 }

提交文件/文件功能

async submitDocument(doc) {

        const url = <removed>;

        const body = doc;

        let headers = new Headers();
        headers.set('Authorization', this.authorization);

        const request = {
            method: 'POST',
            body: body,
            headers: headers,
        };

        try {
            const response = await fetch(url, request);
            const data = await response.json();

            return {
                response: response,
                data: data,
            };

        } catch (err) {
            throw err;
        }

    }

这似乎不起作用,因为。 submitDocument 抛出 catch 错误

SyntaxError: JSON 输入意外结束

【问题讨论】:

  • 什么是api的HTTP状态码
  • 控制台。在网络标签中记录请求

标签: javascript fetch


【解决方案1】:

创建一个new FormData() 并将文档附加到它, 例如

const form = new FormData(); 
form.append('file', doc);

然后将您创建的表单发送到您的正文请求中。

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2018-07-30
    • 1970-01-01
    • 2022-11-22
    • 2015-08-12
    相关资源
    最近更新 更多