简体   繁体   中英

JavaScript new formData().append is not working for uploaded files

In my Reactjs application, I'm sending an uploaded file with some data to API with AXIOS. After a work around, I setup the following code and trying to send it to the back end. However I can't send a file to the API. After input a file and send it to the API, the Request Payload in Network tab shows the uploaded file variable as Empty {} always . How can I solve this?

uploadFile(event) {
        let file = event.target.files[0];
        let data = new FormData();
        data.append('file', file);

        const files = [
            {
                name: "n1",
                description: "d1",
                file: data,
                business_file_type: 1
            }
        ];
        const project_id = 1;

        const allData = { files, project_id }

        API.post('project/files/upload', allData)
            .then(({ data }) => {
                console.log("success", data);
            })
            .catch((err) => {
                console.log("AXIOS ERROR: ", err);
            })
    }

<input className={classes.input} type="file" id="fileInput" name="ifile" onChange={this.uploadFile} />

try this: pass everything in form data.

data.append('file', file);

const files_related_data = [
    {
        name: "n1",
        description: "d1",
        business_file_type: 1
    }
];
const project_id = 1;
data.append('files_related_data', files_related_data);
data.append('project_id', project_id);

const allData = data;

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