0

I am using formdata for file upload operations...

How do I load the data in array format (one of the properties type is file).

JSON.stringify didn't work

How I use it on the controller side

public class SampleData
{
    public string t { get; set; }
    public HttpPostedFileBase u { get; set; }
    public SampleData() { }
}
public JsonResult Save(FormCollection model, SampleData[] upls) {
  ...
}

sample data

var data = [{t:"lorem",u: file}, {t:"ipsum",u: file}, { t:"generator", u: file}];

I tried to formdata append in 3 different structures below, but i didn't succeed

My source for the third example

$.each(data, function(index,vs) {
   formdata.append('upls[]', vs); // Sample 1
})

$.each(data, function(index,vs) {
   formdata.append('upls[][t]', vs.t); // Sample 2
   formdata.append('upls[][u]', vs.u);
});

$.each(data, function(index,vs) {
   var f = new Array(); // Sample 3
   f.t = vs.t;
   f.u = vs.u;
   formdata.append('upls[]', f);
});
Uğur Demirel
  • 71
  • 1
  • 2
  • 9

1 Answers1

0

Instead of using loop directly to append data try to use Object loop as below:-

Object.entries(data).forEach(entry => {
      const [key, value] = entry;
      formData.append(key, JSON.stringify(value));
  })

Here is how you can check it by looping formdata:-

  for(let [key, value] of formData) {
    alert(`${key} = ${value}`); // key1 = value1, then key2 = value2
  }

Full code:-

  let formData = new FormData();
  Object.entries(data).forEach(entry => {
      const [key, value] = entry;
      formData.append(key, JSON.stringify(value));
  })
  for(let [key, value] of formData) {
    alert(`${key} = ${value}`); // key1 = value1, then key2 = value2
  }
Predator13
  • 91
  • 4