1

Following is my code for file upload.

<form encType="multipart/form-data" action="">
    <input type="file" name="fileName" defaultValue="fileName"></input>
    <input type="button" value="upload" onClick={this.handleClick.bind(this)}></input>
</form>


handleClick(){
            let deliveryId = this.props.params.deliveryId;
            var data = new FormData();
            var imagedata = document.querySelector('input[type="file"]').files[0];
            data.append("data", imagedata);
            console.log('Data', data);

            fetch(apiBaseUrl, {
                mode: 'no-cors',
                method: "POST",
                body: JSON.stringify({
                    'item_file': data,
                    'delivery_id': deliveryId,
                    'description': 'test description'
                })
            }).then(function (res) {
                if (res.ok) {
                    alert("Perfect! ");
                } else if (res.status == 401) {
                    alert("Oops! ");
                }
            }, function (e) {
                alert("Error submitting form!");
            });
        }

Though, I can see the file details in 'imagedata', 'data' is coming empty. I am not able to figure out why 'data' is empty. That's why the backend call is failing.

Following is the request payload going to the server after submit:

{item_file: {}, delivery_id: "eeb9422e-9805-48eb-a8be-ad2e27f3f643", description: "test description"}

1 Answer 1

2

You can use FormData itself to achieve file upload with extra parameters like deliveryId. And you can't stringify the file.

 handleClick() {
    let deliveryId = this.props.params.deliveryId;
    var imagedata = document.querySelector('input[type="file"]').files[0];

    var data = new FormData();
    data.append("item_file", imagedata);
    data.append('delivery_id', deliveryId);
    data.append('description', 'test description');

    fetch(apiBaseUrl, {
        mode: 'no-cors',
        method: "POST",
        body: data
    }).then(function (res) {
        if (res.ok) {
            alert("Perfect! ");
        } else if (res.status == 401) {
            alert("Oops! ");
        }
    }, function (e) {
        alert("Error submitting form!");
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.