Send Object array as Ajax parameter

Asked

Viewed 248 times

0

I have an array of objects composed as follows:

{file: File(871699), x: 0, y: 0, width: 2, height: 2, …}

Each vector box has an element as described above, and the first parameter, the file is an image that has the following data:

file:File(871699) {name: "tumblr_lxjy8kfFeQ1qh59n0o1_500.gif", lastModified: 1518121346035, lastModifiedDate: Thu Feb 08 2018 18:22:26 GMT-0200 (-02), webkitRelativePath: "", size: 871699, …}

I would like to pass this array through an ajax call, but I can’t. This is my code:

function uploadFiles(formData) {
    
    $.ajax({
        url: '/admin/foto',
        type: 'POST',
        data: arrayObj,
        contentType: false,
        success: () => {
            console.log("Sucesso!!");
        }
    });
}

And on the server I get as follows:

application.post('/admin/foto', (req, res) => {	
  application.controllers.admin.albums.uploadFotos(application, req, res);
});

1 answer

0


Give a JSON.stringify in the data.

function uploadFiles(formData) {
    const email = "blablablabla";

    $.ajax({
        url: '/admin/foto',
        type: 'POST',
        data: JSON.stringify(arrayObj), // <<-- Stringify
        contentType: false,
        success: () => {
            console.log("Sucesso!!");
        }
    });
}

I assume you’re using the bodyParser, then your data will be on req.body:

application.post('/admin/foto', (req, res) => { 
  console.log(req.body); // <<-- array de objetos
  application.controllers.admin.albums.uploadFotos(application, req, res);
});
  • I did this, but in doing so the file object contained within the vector is lost, it looks as if it is empty

  • Do you want to upload these files? If it is, it will never work...

  • Yes. I am not using formData because I also need to pass x, y, width and height which is calculated in another function. So I put in an array of objects, because there I pass the image and these related values together

  • Got it @Laisaguiar, you can use the Header to pass this information, or create Fields on formdata to put this information. Passing only the objects will not work. Take a look in that reply and in this tutorial, maybe it’ll help you.

  • Thanks @Kaduamaral going through the header I got to do what I needed!! Thanks anyway

Browser other questions tagged

You are not signed in. Login or sign up in order to post.