Save image file in sdcard in firefox OS - javascript

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.

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);
}
});

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.

Related

How to use XPCOM in iMacros to load data and write data

These are the functions which load file and write file. I used JavaScript and XPCOM for these operations. You can use these functions in iMacros JavaScript file.
Edit: These functions work best in iMacros version 8.9.7 and corresponding Firefox. The later versions of iMacros addon don't support JavaScript. Also it's best to use Firefox 47 with disabled updates. And you can use latest Pale Moon browser with addon 8.9.7 . If there is a content in file the WriteFile function simply adds data in new line.
//This function load content of the file from a location
//Example: LoadFile("C:\\test\\test.txt")
function LoadFile(path) {
try {
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var file = new FileUtils.File(path);
file.initWithPath(path);
var charset = 'UTF8';
var fileStream = Components.classes['#mozilla.org/network/file-input-stream;1']
.createInstance(Components.interfaces.nsIFileInputStream);
fileStream.init(file, 1, 0, false);
var converterStream = Components.classes['#mozilla.org/intl/converter-input-stream;1']
.createInstance(Components.interfaces.nsIConverterInputStream);
converterStream.init(fileStream, charset, fileStream.available(),
converterStream.DEFAULT_REPLACEMENT_CHARACTER);
var out = {};
converterStream.readString(fileStream.available(), out);
var fileContents = out.value;
converterStream.close();
fileStream.close();
return fileContents;
} catch (e) {
alert("Error " + e + "\nPath" + path)
}
}
//This function writes string into a file
function WriteFile(path, string) {
try {
//import FileUtils.jsm
Components.utils.import("resource://gre/modules/FileUtils.jsm");
//declare file
var file = new FileUtils.File(path);
//declare file path
file.initWithPath(path);
//if it exists move on if not create it
if (!file.exists()) {
file.create(file.NORMAL_FILE_TYPE, 0666);
}
var charset = 'UTF8';
var fileStream = Components.classes['#mozilla.org/network/file-output-stream;1']
.createInstance(Components.interfaces.nsIFileOutputStream);
fileStream.init(file, 18, 0x200, false);
var converterStream = Components
.classes['#mozilla.org/intl/converter-output-stream;1']
.createInstance(Components.interfaces.nsIConverterOutputStream);
converterStream.init(fileStream, charset, string.length,
Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
//write file to location
converterStream.writeString(string + "\r\n");
converterStream.close();
fileStream.close();
} catch (e) {
alert("Error " + e + "\nPath" + path)
}
}
//this function removes file from location
function RemoveFile(path) {
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
//file.initWithPath("c:\\batstarter6_ff.cmd");
file.initWithPath(path);
/*
var file = IO.newFile(path, name);
*/
file.remove(false);
}
// Download a file form a url.
function saveFile(url) {
try {
// Get file name from url.
var filename = url.substring(url.lastIndexOf("/") + 1).split("?")[0];
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function () {
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response is a blob
a.download = filename; // Set the file name.
a.style.display = 'none';
document.body.appendChild(a);
a.click();
delete a;
};
xhr.open('GET', url);
xhr.send();
} catch (e) {
alert("Error " + e)
}
}
/*
This function runs file from given path
*/
function RunFile(path) {
var file = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
//file.initWithPath("c:\\batstarter6_ff.cmd");
file.initWithPath(path);
file.launch();
}
//this function downloads a file from url
function downloadFile(httpLoc, path) {
try {
//new obj_URI object
var obj_URI = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(httpLoc, null, null);
//new file object
var obj_TargetFile = Components.classes["#mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
//set file with path
obj_TargetFile.initWithPath(path);
//if file doesn't exist, create
if (!obj_TargetFile.exists()) {
obj_TargetFile.create(0x00, 0644);
}
//new persitence object
var obj_Persist = Components.classes["#mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Components.interfaces.nsIWebBrowserPersist);
// with persist flags if desired
const nsIWBP = Components.interfaces.nsIWebBrowserPersist;
const flags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
obj_Persist.persistFlags = flags | nsIWBP.PERSIST_FLAGS_FROM_CACHE;
/*
var privacyContext = sourceWindow.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsILoadContext);*/
//save file to target
obj_Persist.saveURI(obj_URI, null, null, null, null, obj_TargetFile, null);
} catch (e) {
alert(e);
}
}
//This function prompts user to select file from folder and use it
function PickFile(title) {
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["#mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
fp.init(window, title, nsIFilePicker.modeOpen);
fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
var rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
var file = fp.file;
// Get the path as string. Note that you usually won't
// need to work with the string paths.
var path = fp.file.path;
// work with returned nsILocalFile...
return path;
}
}
//This function prompts user to select folder from folder and use it
function PickFolder(title) {
var picker = Components.classes["#mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
picker.appendFilters(Components.interfaces.nsIFilePicker.filterAll);
//folder
picker.init(window, title, Components.interfaces.nsIFilePicker.modeGetFolder);
//or file
// picker.init (window, "Choice file", Components.interfaces.nsIFilePicker.modeOpen);
if (picker.show() == Components.interfaces.nsIFilePicker.returnOK) {
return picker.file.path;
} else {
return false;
}
}
//this function offers a set of options to select from
//items is an array of options
//title is the dialog title
//qustion is a question asked to user.
function Select(items, title, question) {
var prompts = Components.classes["#mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
//var items = ["Articles", "Modules", "Both"]; // list items
var selected = {};
var result = prompts.select(null, title, question, items.length,
items, selected);
// result is true if OK was pressed, false if cancel. selected is the index of the item array
// that was selected. Get the item using items[selected.value].
var selected = items[selected.value];
return selected;
}
Edit: I am also adding iMacros version 8.9.7 addon to download because version 10 doesn't support JavaScript http://download.imacros.net/imacros_for_firefox-8.9.7-fx.xpi
Edit1: I added some more useful functions for iMacros.

Firebase Storage: "Invalid argument in put at index 0: Expected Blob or File

I keep getting an Invalid argument in put at index 0: Expected Blob or File error. The funny thing is the argument is totally a file...
Here is the code:
var file = document.getElementById('cke_69_fileInput')
.contentWindow.document.getElementById('cke_69_fileInput_input').files[0];
var storageUrl = 'noticias/imagenes/';
var storageRef = firebase.storage().ref(storageUrl + file.name);
console.warn(file); // Watch Screenshot
var uploadTask = storageRef.put(file);
Here's the screenshot of the actual file warn just before the error asking for a file...
try converting file to blob...
var reader = new FileReader();
reader.onloadend = function (evt) {
var blob = new Blob([evt.target.result], { type: "image/jpeg" });
var storageUrl = 'noticias/imagenes/';
var storageRef = firebase.storage().ref(storageUrl + file.name);
console.warn(file); // Watch Screenshot
var uploadTask = storageRef.put(blob);
}
reader.onerror = function (e) {
console.log("Failed file read: " + e.toString());
};
reader.readAsArrayBuffer(file);

Cordova write PDF to file

I whant to write a Cordova App for BlackBerry10 that can write a PDF file (from a SharePointWebservice) and show it.
The PDF is transmitted from a ASP.NET Webservice as byte[] using
byte[] result = spFile.OpenBinary();
I'm able to access the file with JSON. This works fine.
To transform the data fromm JSON to usable format I use the following code:
var binary = '';
var bytes = new Uint8Array(data.d);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(data.d[i]);
}
binary is now looking like that:
%PDF-1.5%ยตยตยตยต 1 0 obj ... startxref 103423 %%EOF
Here is the Code to write it to a file using cordova-plugin-file.
var blob = new Blob([binary], { type: 'application/pdf' });
fileWriter.write(blob);
It works fine for txt files, but when I try to write the PDF file I get an empty document.
I have also tryed window.btoa(binary) instead of just using binary.
Any ideas what ho to create the data blob, or which format to use?
I have solved the Problem by using the cordova fileOpener2 Plugin. I am using the var "bytes" from above filled into the new named variable data.
try {
window.resolveLocalFileSystemURL(cordova.file.externalApplicationStorageDirectory, function (directoryEntry) {
directoryEntry.getFile(fileName, { create: true }, function (fileEntry) {
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function (e) {
cordova.plugins.fileOpener2.open(cordova.file.externalApplicationStorageDirectory + fileName, 'application/pdf',
{
error: function (e) {
...
},
success: function () {
... //PDF has opened
}
}
);
};
fileWriter.onerror = function (e) {
...
};
//Blob erstellen - Blackberry File Plugin verwenden
var blob = new Blob([data], { type: 'application/pdf' });
fileWriter.write(blob);
}, function onerror(e) {
...
});
}, function onerror(e) {
...
});
}, function onerror(e) {
...
});
} catch (e) {
...
}
Used Plugins:
cordova-plugin-file &
cordova-plugin-file-opener2
For other file types like PNG I use (for jpg just replace png with jpg):
var blob = new Blob([data], { type: 'image/png' });
to write the file and
window.open(cordova.file.externalApplicationStorageDirectory + fileName);
to open and show it.
Showing txt files is quite easy, you can do it like that:
if (fileName.split('.')[1].indexOf("txt") > -1) {
var blob = new Blob([bytes], { type: 'text/plain' });
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
This worked for me, comment if you have any questions.

how to store audio file in Sdcard captured using getUserMedia in fire fox os

i am creating one app where when i will press save button it will store given blob audion data in to SDcard in firefox os here i am presenting code for it.
var audioURL = window.URL.createObjectURL(e.data);
audio.src = audioURL;
audio.type="video/ogg";
deleteButton.onclick = function(e) {
evtTgt = e.target;
evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
}
saveButton.onclick = function(e) {
evtTgt = e.target;
var sdcard = navigator.getDeviceStorage("sdcard");
var file = new Blob([audioURL], {type: "video/ogg"});
var request = sdcard.addNamed(file, "my-file.ogg");
request.onsuccess = function () {
var name = this.result;
console.log('File "' + name + '" successfully wrote on the sdcard storage area');
}
here i have written the code but it is not working.so plz any one can help??
I assume you get the data from the MediaRecorder event object that is passed to the handler of the "dataavailable" event like in the example outlined here: https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder/ondataavailable
In this case e.data is already a Blob and you can simply pass it to the addNamed function as documented here: https://developer.mozilla.org/en-US/docs/Web/API/DeviceStorage/addNamed
var audioData = e.data,
audioURL = window.URL.createObjectURL(e.data);
audio.src = audioURL;
audio.type ="video/ogg";
deleteButton.onclick = function(e) {
evtTgt = e.target;
evtTgt.parentNode.parentNode.removeChild(evtTgt.parentNode);
}
saveButton.onclick = function(e) {
evtTgt = e.target;
var sdcard = navigator.getDeviceStorage("sdcard");
var request = sdcard.addNamed(audioData, "my-file.ogg");
request.onsuccess = function () {
var name = this.result;
console.log('File "' + name + '" successfully wrote on the sdcard storage area');
}
}
However, you should double-check your code since it seems to have unmatching brackets.

Get base64 of audio data from Cordova Capture

I am using ngCordova Capture to write this code by recording audio and send the base64 somewhere (via REST). I could get the Capture Audio to work but once it returns the audioURI, I cannot get the data from the filesystem as base64. My code is below:
$cordovaCapture.captureAudio(options).then(function(audioURI) {
$scope.post.tracId = $scope.tracId;
$scope.post.type = 'audio';
console.log('audioURI:');
console.log(audioURI);
var path = audioURI[0].localURL;
console.log('path:');
console.log(path);
window.resolveLocalFileSystemURL(path, function(fileObj) {
var reader = new FileReader();
console.log('fileObj:');
console.log(fileObj);
reader.onloadend = function (event) {
console.log('reader.result:');
console.log(reader.result);
console.log('event.result:');
console.log(event.result);
}
reader.onload = function(event2) {
console.log('event2.result:');
console.log(event2.target.result);
};
reader.readAsDataURL(fileObj);
console.log(fileObj.filesystem.root.nativeURL + ' ' + fileObj.name);
$cordovaFile.readAsDataURL(fileObj.filesystem.root.nativeURL, fileObj.name)
.then(function (success) {
console.log('success:');
console.log(success);
}, function (error) {
// error
});
});
Here is the output in console log:
So how do I get the base64 data from the .wav file?
I have been reading these links:
PhoneGap FileReader/readAsDataURL Not Triggering Callbacks
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
http://jsfiddle.net/eliseosoto/JHQnk/
http://community.phonegap.com/nitobi/topics/filereader_onload_not_working_with_phonegap_build_2_5_0
Had same problem, which I fixed using both the Cordova Capture and Cordova File plugin.
navigator.device.capture.captureAudio(function (audioFiles) {
var audioFile = audioFiles[0],
fileReader = new FileReader(),
file;
fileReader.onload = function (readerEvt) {
var base64 = readerEvt.target.result;
};
//fileReader.reasAsDataURL(audioFile); //This will result in your problem.
file = new window.File(audioFile.name, audioFile.localURL,
audioFile.type, audioFile.lastModifiedDate, audioFile.size);
fileReader.readAsDataURL(file); //This will result in the solution.
});

Categories

Resources