Sending blob data via ajax

7k views Asked by At

So I'm trying to send an image via ajax as a blob. The blob has the correct type and is about 4.5 kb in size. I try to send it like this:

document.getElementById("canvas").toBlob(function (blob) {
    var data = new FormData();
    data.append('name', name);
    data.append('program', YouTomaton.Main.get_CurrentProgram());
    data.append('image', blob);
    $.ajax({
        type: "Post",
        url: "save.php",
        data: data,
        processData: false,
        contentType: false,
        success: function (result) {
            if(result != undefined && result.length > 0)
                alert(result);
        }
    });
});

The recieving page looks like this:

<?php
include("session.php");
writeProgram($_POST['name'], $_POST['program'], $_POST['image']);
?>

It tells me that the index 'image' could not be found. So not only does the data not get sent, but even the index is omitted. What am I doing wrong ?

EDIT: neither toBlob nor toDataURL produce anything but an empty PNG. Is there a way to convert the data from a framebuffer into a base64 encoded jpg or png ?

2

There are 2 answers

4
Jake OS On

Read this. Then think of what you would like to do.

If you could use a plugin for jQuery. I would recommend using FileUpload

For an HTML file input, minimal syntax would be like this:

<input type="file" name="fs" id="fileupload" />

And JS script:

$('#fileupload').fileupload({
                url: "fileupload?additional=data",
                done: function (e, data) {
                    console.log(data.result);
                }
            }).prop('disabled', !$.support.fileInput)
                .parent().addClass($.support.fileInput ? undefined : 'disabled');
0
MJHd On

I'm working on a similar problem right now - I'm using PDF's - here's my working ajax call:

$.ajax({
            dataType: "native",
            url: ("handle.php?filename=" + event.target.dataset.name),
            xhrFields: { responseType: "blob" },
            data: "secure=<?php echo $pass ?>",
            success: function(result){
                    console.log(result.size)
                    download(result, event.target.dataset.name, "application/pdf")
            }
        })

The download() part is a call to the FileSaver tool - which is how the Blob gets saved on the client side in my case...

I'm using data-name attr in the markup to store JUST the filename (not full path) - hope that helps!

EDIT:: Sorry for the PHP mixed in! - that statement just passes a hashed nonce token to the script to make sure no requests have been duplicated/gotton out of order - etc...