bonaca bonaca - 9 months ago 29
jQuery Question

pick an image and upload it automatically

I want to click on a button and open the file browser from a local disc and automatically upload the selected file to remote server.

<input hidden type="file" id="loader" accept="image/*">


js

$('#m1new').click(function(){
$('#loader').click();
});
$('#loader').change(function(){
var img = this.files[0];
$.ajax({
url: 'upload.php',
type: 'post',
data: {'img': img},
success: function() {
console.log('ok');
}
});
});


upload.php (updated)

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
move_uploaded_file($_FILES["img"]["tmp_name"], $target_file);


Console:
Uncaught TypeError: Illegal invocation


Any help?

Answer Source

Use FormData to send multipart requests and you should set processData option to false to preven automatic processing

$('#loader').change(function(event){
  var img = event.target.files[0];
  var formData = new FormData();
  formData.append('img', img);
  $.ajax({
      url: 'upload.php',
      processData: false,
      type: 'post',
      data: formData,
      success: function() {
        console.log('ok');
      }
  }); 
});

Hope this will be helpful