user3026745
user3026745

Reputation: 15

How to send an image through ajax post?

I'm trying to send some data through ajax post, I tried serializ but I keep getting an error the filename doesn't exist. Form data

$('#send #submit').on('click', function(e){
  e.preventDefault();
  $.post( "send.php", $("#bend").serialize())
    .done(function( data ) {
      alert( "Data Loaded: " + data );
    });
});

When you click submit first thing I try is to get file size I get

Warning: getimagesize(): Filename cannot be empty

$dateityp = GetImageSize($_FILES['datei']['tmp_name']);

Upvotes: 0

Views: 5913

Answers (2)

juli savani
juli savani

Reputation: 27

 var file_data = $('#truckattachmentForm #receipts').prop('files')[0];
        var form_data = new FormData($('#truckattachmentForm')[0]);
        form_data.append('file', file_data);
        $.ajax({
            url: web_url + '/admin/truck/storeTruckAttachment',
            type: "POST",
            dataType: "json",
            data: form_data,
            cache: false,
            contentType: false,
            processData: false,
            statusCode: {
                200: function (xhr) {}
            }
      });

Upvotes: 0

Aaron
Aaron

Reputation: 3255

You can convert to base64. One way to do that is to draw the image to a canvas and use .toDataURL.

You can pass the image to this function I found on google for a base64 encode:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

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

Then upload through AJAX like this:

$.ajax({
  type: "POST",
  url: "send.php",
  data: {image: img}
}).done(function( respond ) {
  console.log(respond);
});

Upvotes: 2

Related Questions