0

I need to upload image using ajax. Elaborating my point: I need to pass my image data to a PHP page and check the type, size, name and all other attributes of the file. If all attributes matches, then only I need to transfer the file. Problem here is passing of data should be done in JSON(AJAX) format only. One more important thing is that I don't have to convert it to base64.

If you can help me in this, You are most welcome.

Thanks in advance.

PJU
  • 25
  • 8
Vineet Mishra
  • 100
  • 1
  • 11

1 Answers1

2

The idea in SO is to work on the OP current code. I mean, we are not here to make all the job, because it should have a price. Anyway, here is a workaround for your issue:

Convert your image to base64 using javascript. This useful method works like a charm:

// Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479)
function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to guess the
    // original format, but be aware the using "image/jpg" will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then just pass the returned string as base64 through ajax:

$.ajax({
    url: 'path/to/your/script.php',
    type: 'post',
    data: { paramName: imagedata } // the returned data from above js method,
    /*...*/
});

And, in PHP side, just return the string to an image file:

// Code taken from Austin Brunkhorst (http://stackoverflow.com/a/15153931/3648578)
function base64_to_jpeg($base64_string, $output_file) {
    $ifp = fopen($output_file, "wb"); 

    $data = explode(',', $base64_string);

    fwrite($ifp, base64_decode($data[1])); 
    fclose($ifp); 

    return $output_file; 
}
kosmos
  • 4,253
  • 1
  • 18
  • 36
  • Thanks @kmsdev. I will try this and let you know about the update. – Vineet Mishra May 11 '15 at 10:04
  • You are welcome, hope you achieve it. Pay attention to the ajax method, which requires jQuery – kosmos May 11 '15 at 10:10
  • Your answer worked for me. But just now some requireent has been changed. So I modified code. But still getting some issue. Can you look into it - [http://stackoverflow.com/questions/30166082/how-to-fetch-data-from-ajax-in-php] – Vineet Mishra May 11 '15 at 11:09