Christian
Christian

Reputation: 194

converting Dropzone File object to base64 string

I am trying to send Dropzone File Using JSON so I want to decode the image into base64 I tried this function:

function getBase64Image(imgElem) {
    var canvas = document.createElement("canvas");
    canvas.width = imgElem.clientWidth;
    canvas.height = imgElem.clientHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgElem, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

now for Dropzone I write this to test the base64 converter

$("form#dropzone").dropzone({
    url: allPaths.baseUrl + 'Services/PictureUpload.asmx/HandleFileDropped',
    uploadMultiple: true,
    autoProcessQueue: false,
    acceptedFiles: "image/*",
    init: function() {
        this.on("addedfile", function(file) {
            console.log(getBase64Image(file));
        });
    }    
});

and I got the error that File object is not valid

Upvotes: 4

Views: 8782

Answers (2)

Danielle Lpz
Danielle Lpz

Reputation: 322

I used a different approach since I save trough a json object in Ajax.

First, I declared an global array.

images = [];

I acceded to the files in my dropzone area like this, and pushed them to my array images.

 for (var i = 0; i < $animalImage.files.length; i++) {
            images.push($animalImage.files[i]);
        }

Second I added that array to my json object(animal) mapping them with the info that I was expecting in my Model(asp.net C#)

 animal.Pictures = $.map(images, function (img) {
            return {
                base64: img.dataURL.replace(/^data:image\/[a-z]+;base64,/, ""),
                fileName: img.name,
                type: img.type
            };
        });

As you can see I mapped base64, information that I got from the image.

Hope it helps.

Upvotes: 3

Christian
Christian

Reputation: 194

I found that the file.DATAURL has the base64 already (without the needing of the above function) so I will post my solution here:

 $("form#dropzone").dropzone({
        url: allPaths.baseUrl + 'Services/PictureUpload.asmx/HandleFileDropped',
        uploadMultiple: true,
        autoProcessQueue: false,
        acceptedFiles: "image/*",
        init: function() {
            this.on("addedfile", function (file) {
                var reader = new FileReader();
                reader.onload = function(event) {
                    // event.target.result contains base64 encoded image
                    var base64String = event.target.result;
                    var fileName = file.name
                    handlePictureDropUpload(base64String ,fileName );
                };
                reader.readAsDataURL(file);

            });
        }

    });

Upvotes: 8

Related Questions