Question

I am trying to save an image in sdcard. I am following this documentation.

$('.btnSave').on('click', function () {

        var imageRawData = canvas.toDataURL("image/png") ;
        var sdcard = navigator.getDeviceStorage("sdcard");
        var file = new Blob([imageRawData], { type: "image/png" });
        var request = sdcard.addNamed(file, "FilertedImage.png");

                request.onsuccess = function () {
                var name = this.result;
                console.log('File "' + name + '" successfully wrote on the sdcard storage area');

                }
                request.onerror = function (e) {
                console.log('Unable to write the file: ' + e.target.error.name);

                }
    }); 

In the documentation I found that "pictures only accepts Blob with a valid image mime type". So how can I convert imageRawData to valid image mime type using javascript.

Was it helpful?

Solution

I have done it like the following - Saves and then shares:

 function saveAndSend(blob) {
     var sdcard = navigator.getDeviceStorage("sdcard");
     var request = sdcard.addNamed(blob, "test/mycanvas.png");

     //could just share the blob instead of saving
     request.onsuccess = function () {
         var sharingImage = new MozActivity({
             name: "share",
             data: {
                 type: "image/*",
                 number: 1,
                 blobs: [blob],
                 filenames: ["mycanvas.png"],
                 filepaths: ["test/mycanvas.png"]
             }
         });
     }

     // An error could occur if a file with the same name already exist
     request.onerror = function () {
         alert('Unable to write the file: ' + this.error.name);
     }

 }


 var cnv = document.getElementById('myCanvas');
 cnv.toBlob(function (blob) {

     //var sdcard = navigator.getDeviceStorage("pictures");
     var sdcard = navigator.getDeviceStorage("sdcard");
     var request = sdcard.delete("test/mycanvas.png");
     //try to delete in case it exists
     request.onsuccess = function () {
         saveAndSend(blob);
     }

     request.onerror = function () {
         saveAndSend(blob);
     }


 });

OTHER TIPS

Your app also need to make sure that it has the appropriate device storage permissions.

See: https://github.com/mozilla-b2g/gaia/blob/master/dev_apps/ds-test/manifest.webapp#L13 for an example. ds-test is a test app I wrote for testing things in device storage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top