0

I'm trying to choose an image from PC/mobile and upload it to the server on one button click but for some reason I can't grab the value (name) of chosen image - $_FILES["pictureCapture"]["name"] inside PHP page. I can do it easily using two buttons, one to browse for the image on my device and second to upload it but I really need one button click for these two procedures.

My source code:

HTML

<form action="" method="post" enctype="multipart/form-data" onsubmit="test3()">
    Select image to upload:
    <input type="file" name="pictureCapture" id="pictureCapture" accept="image/*; capture=camera" style="visibility:hidden;" onchange="test2();"/>
    <button type="button" id="uploadPhotoFromCamera" onclick="test();">Choose an image</button>
    <input id="uploadPhotoToServer" type="submit" value="Upload Image" name="submit" style="visibility:hidden;"/>
</form>

jQuery + AJAX

function test(){  
   event.preventDefault();
   $("#pictureCapture").trigger("click");
}

function test2(){   
    $("#uploadPhotoToServer").trigger("click");
}

   function test3(){
      event.preventDefault();

      var formData = new FormData();
      var fileInput = document.getElementById('pictureCapture');
      formData.append(fileInput.files[0].name, fileInput.files[0]);   

      $.ajax({
          url : "upload.php", // Url to which the request is send
          type : "POST", // Type of request to be send, called as method
          data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
          cache : false, // To unable request pages to be cached
          processData : false, // To send DOMDocument or non processed data file it is set to false
          contentType: 'multipart/form-data',
        success : function(result) // A function to be called if request succeeds
        {
            alert(result);
        }
    });
}

PHP

$target_dir = "uploads/";
$target_file = $target_dir .date('d-m-Y-H-i-s').'-'. basename($_FILES["pictureCapture"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["pictureCapture"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["pictureCapture"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["pictureCapture"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

Please could you help me to sort this issue!

4
  • Maybe with test2 to trigger the form submit? Commented Dec 14, 2016 at 14:38
  • @dimis283, well I know it will work the way you suggested but I need to use AJAX in order to display an error or success message inside my html page Commented Dec 14, 2016 at 14:42
  • I mean something like this airpair.com/js/jquery-ajax-post-tutorial view the 2 AJAX POST Example, the jQuery way Commented Dec 14, 2016 at 14:48
  • On a sidenote - do not use getimagesize to check if the file is a valid image file. php.net/manual/en/… Commented Dec 14, 2016 at 14:58

2 Answers 2

1

You need to populate your FormData() with your file data:

var formData = new FormData();
$.each($('pictureCapture')[0].files, function(key, value) {
    formData.append(key, value);
});

Add change your contentType to multipart in your jQuery ajax call:

$.ajax({
    ...
    data: formData, 
    ...
    contentType: 'multipart/form-data',
    ...
Sign up to request clarification or add additional context in comments.

7 Comments

Did you remove the contentType: false line?
Yes I did but still nothing!
You also forgot to add your file data to the FormData object. Check edits.
I've got this error now - Uncaught TypeError: Cannot read property 'files' of undefined
have a look at my updated script, still cant grab the file name :(
|
0

Why not just submit the form automatically using onchange on the file input? As soon as they select a file, it will submit the image for them. Here is a jsfiddle.

Or as is applies to your situation:

$(document).ready(function(){
    $('#pictureCapture').change(function(){
        this.form.submit();
    });
});

1 Comment

Fair enough but I need to use AJAX in order to display an error or success message inside my html page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.