0

I need to upload file within multiple objects. I am able to upload single file or multiple file using form data.

Below sample is working fine.

var form_data = new FormData();
form_data.Append("test","test")
form_data.Append("test","test")
form_data.Append("file",file)
form_data.Append("file1",file1)

My issue is that how to upload data like this.

var obj = {
           "field1":"test",
           "field2","test", 
           "childObj": [
               {"filed1:"test","field2":"test","file":file},
               {"filed1:"test","field2":"test","file":file},
               {"filed1:"test","field2":"test","file":file}
            }]
          }

here child object is dynamically added using jQuery. so it is n number of children and every child contains one file that will be uploaded by HTML input tag file.

I want to upload this JSON data using Ajax.

7
  • Did you as a user actively allow the browser to load your file during your test? Commented Mar 26, 2024 at 20:12
  • You can't put file uploads in JSON. Commented Mar 26, 2024 at 20:14
  • @barmar is there any alternet way to upload json like this? Commented Mar 26, 2024 at 20:16
  • @lajosarpad my requirement is that I want to upload data with one parent record and other records are child with detail and file. Commented Mar 26, 2024 at 20:17
  • @PravinTukadiya yes, that's understood. But you will not be able to upload a file without the user wanting it. Imagine a case when you are opening a page and that page, without your consent would simply upload some files from your filesystem. Of course this is extreme security concern and browsers do not support this. So, I'm asking the question again: did you, as a user actively upload your file during your test? Commented Mar 27, 2024 at 10:36

1 Answer 1

0

You can't put a file upload inside JSON. You should send the JSON in a separate parameter.

let obj = {
  "field1":"test",
  "field2","test", 
  "childObj": [
     {"field1":"test","field2":"test"},
     {"field1":"test","field2":"test"},
     {"filed1":"test","field2":"test"}
  }]
};

let form_data = new FormData();
form_data.append("obj", JSON.stringify(obj));
form_data.Append("file", file);
form_data.Append("file1", file1);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.