简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM