Upload image with JS

Asked

Viewed 136 times

1

Good afternoon, I’m trying to upload image using JS but I’m not getting, I’m not using jQuery, I’m using Axios.

Until now, I tried that way

var files = document.getElementById("inputPhoto").files;

axios.post(url+'api.php', {
        file: new FormData(imagem])
    }, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(function(response){
        console.log(response)
    })
    .catch(function(error){
        console.log(error)
    })

NOTE: I am using HTML5 Multiple, Backend is already ready in PHP

  • You have a syntax error here new FormData(imagem]) and this variable is not in the question code... Some error in the console?

  • in fact the image is the variable files, it was my mistake when writing here, but the code is right

  • You have tested in the "official" way https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html#L25-L35 ?

  • @Sergio I will try, but there is an example to work with one photo at a time, wanted with several, using the Multiple

  • @Sergio that way worked, but I can still only recover an image

1 answer

2


According to repository suggestions on Github, you can simply join Formdata:

var files = document.getElementById("inputPhoto").files;
let data = new FormData();

for (var i = 0, l = files.length; i < l; i++) {
  let file = files.item(i);
  data.append('images[' + i + ']', file, file.name);
}

const config = {
  headers: {
    'content-type': 'multipart/form-data'
  }
}

axios.post('/api/images', data, config);

Browser other questions tagged

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