简体   繁体   中英

how do I send a request using multipart/form-data?

I have an app in ReactJs, using Axios and Papaparse.

I have a page where a user drop a csv file in a box, I automatically download the csv, update and make some change in the data, and send a new csv file to a server.

I did all until I arrive to the part where I need to create a new csv, and upload it to the server.

Here is my code currently :

            const data = papaparse.unparse(destinationUpdateData, {
                header: true,
                skipEmptyLines: true
            });
            // data is a string in csv format

            const file = new File([data as BlobPart], "destination.csv",  { type: "text/csv" });
            // I get a File type.

            const paramsDestination = {
                project_id: this.props.projectId,
                datastore_id: 'DESTINATIONS',
                file: file,
                id: ["1", "2","3"]
            }
            // the data I would like to send is build

            Axios.post(`new_item_file_attachment`, params, {headers: {"Content-Type": "multipart/form-data"}})
            //I send to the server

The thing is, my server is expecting a request with a content Type of multipart/form-data , but I don't get how manually set my parameter to match this type.

The api call currently don't work, because the data is passed like a json, and the server reject it.

Is it possible to achieve it ?

I tried using FormData , but I can't see how to send boolean and array

Not 100% familiar with Axios but it should be something like this:

var params = new FormData();

params.append("project_id", this.props.projectId);
params.append("datastore_id", 'DESTINATIONS');
params.append("file", file);
params.append("id", JSON.stringify(["1", "2","3"])); // Arrays must be stringified
Axios.post(`new_item_file_attachment`, params)

You definitely need to put everything in FormData object. Last time I was doing this, I also had to remove the "Content-Type": "multipart/form-data" from the header. I believe the correct header should get filled in automatically. Try it with and without that stating a header and let me know if either works.

Here is my solution.

const data = new FormData();
data.append("project_id", id);
data.append("file", file);

axios.post(url, data);

Try and comments when some errors occur.

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