Ti Fi Shu
Ti Fi Shu

Reputation: 67

Submit <img> through jQuery ajax?

My page has a file input. When the user uploads a photo, they then crop it and the result is stored in an img element (using FileReader).

How can I submit this image through jQuery ajax?

EDIT

I got something working. There are 2 problems though. First, the image file size is really big (almost 1MB for a 600x600 picture).
Second, I am not sure how to verify in PHP that the file uploaded is an image.

$pic = $_POST['pic'];

$pic = str_replace('data:image/png;base64,', '', $pic);
$pic = str_replace(' ', '+', $pic);
$pic = base64_decode($pic);

$path = "c:/wwwroot/images/img.jpg";

file_put_contents($path,$pic);

Upvotes: 0

Views: 99

Answers (2)

codenut
codenut

Reputation: 681

you question need more description but as for normal image image upload code is here:

  $(document).on('submit', 'form', function (event) {

        event.preventDefault();

        var form_data = new FormData();

        $($(this).prop('elements')).each(function () {
            if (this.type == 'file')
                form_data.append(this.name, this.files[0]);//here you can upload multiple image by iterating through files[]
            else
                form_data.append(this.name, $(this).val());// for text fields

        });


        $.ajax({
            type: "POST",
            cache: false,
            contentType: false,
            processData: false,
            url: $(this).attr('action'),
            data: form_data,
            beforeSend: function () {

            },
            success: function (data) {

            },
            error: function (data) {

                });
            }
        });

    });

if (this.type == 'file') form_data.append(this.name, this.files[0]);

this will add data from input type file data to form_data and then it will be send by ajax

Upvotes: 0

akdsfjakls
akdsfjakls

Reputation: 208

Using ajax you could read file bytes using FileReader Convert it to base64 and then send it to server. This is how It goes:

var sendingcanvas = document.getElementById('sendingcanvas');
var dataURL = sendingcanvas.toDataURL("image/*");
var imagedatatosend = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

var formdata = new FormData();
formdata = {
    'image': imagedatatosend
};

$.ajax({
    url: 'serverside',
    type: 'POST',
    data: formdata,
    encode: false,
    cache:false,
    success: function(data){}
});

Easy and Recommended Way:

function upload(file, servlet){
var xhr=new XMLHttpRequest(), sres=null;
xhr.onreadystatechange = function() {
    if (xhr.readyState == XMLHttpRequest.DONE) {
        alert(xhr.responseText);
        sres=xhr.responseText;
    }
}
xhr.open('post',servlet,false);
xhr.send(file);
return sres;
}

Call the function Inputing image location and serverside link And you are good to go :)

Upvotes: 1

Related Questions