简体   繁体   中英

How to submit a file using Fetch API from an input element

A user will select an image and then i want to send this image to the backend.

The sending of an image is handled in the body, for example i have successfully tested on postman, i select body -> binary to upload an image directly.

I want to replicate this request using javascript fetch api.

Submission

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

 }

Submit Document/File function

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

    }

It doesn't' seem like this works because. submitDocument throws a catch error

SyntaxError: Unexpected end of JSON input

Create a new FormData() and append to it the document, eg

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

And then send in your body request the form you have created.

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