andyh0316
andyh0316

Reputation: 355

How to upload files along with posting a complex object

I have a page where I can create a developer, which is a complex object, now I need to add upload files functionality to it. I've been trying many ways and still doesnt work. Here is an example (without file upload):

// Frontend: Reactjs
let developer = {
    name: "Andy",
    address: {
        street: "123 Im stupid rd",
        city: "Los Angeles",
        zip: 12345
    },
    tasks: [
        { name: "wake up" },
        { name: "eat" },
        { name: "take a dump" },
        { name: "sleep" }
    ]
}

axios({
    method: "POST",
    url: '/addDeveloper',
    data: developer
})

This would send the developer, with its name, address, and list of tasks into the backend as a complex object and it saves into the database, everything is beautiful.

Now I want to be able to attach a file to each task and I am having world of troubles.

So to start I tried an example with just files, nothing else, and it works, like this:

let formData = new FormData();

let files = ...; // files from input

for (let i = 0; i < files.length; i++) {
  formData.append("files", files[i]);
}

httpRequest({
  method: AppConsts.REQUEST_METHOD_POST,
  url: `/testUpload`,
  data: formData
})

This sends a list of files to the backend to a test controller method, which also work beautifully. But now If i wanna include the files in the complex object everything goes to sh*t and I get a 415 Media Unsupported error:

let files = ...; //  files from input
let developer = {
    name: "Andy",
    address: {
        street: "123 Im stupid rd",
        city: "Los Angeles",
        zip: 12345
    },
    tasks: [
        { name: "wake up", file: files[0] },
        { name: "eat", file: files[1] },
        { name: "take a dump", file: files[2] },
        { name: "sleep", file: files[3] }
    ]
}

axios({
    method: "POST",
    url: '/addDeveloper',
    data: developer
})

I've tried adding contentType multiform header, i've tried adding the whole developer as a formData, and still doesnt work. Maybe I am doing the second part wrong? Someone please help me =(

Upvotes: 0

Views: 743

Answers (1)

poeticGeek
poeticGeek

Reputation: 1041

For files you do need to send formData with multipart. Therefore, I suggest stringifying the json object and adding it to the form data as another parameter.

const developer = {name: "Andy", ...};

formData.append("developer", JSON.stringify(developer));

On the server you will need to parse the JSON but that should be easy.

Upvotes: 1

Related Questions