I tried a simple project using HTML5 FileSystem,
so I can store data in the client-side.
My first trial was a success, because I initiate everything at the start with JavaScript,
and manipulate the file (read the file and append it to the textarea or P; and write/modify the file) in the onclick or onkeypress event.
But, when I do it simultaneously outside of the event, the variable of the filesystem is null/undefined and I can't continue the process.
Here is the code which is working fine:
function initFS() {
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,
function(grantedBytes) {
window.requestFileSystem(window.TEMPORARY, grantedBytes, function (filesystem)
{
fs = filesystem;
}, errorHandler);
});
}
document.body.onclick=function()
{
alert(fs);
fs.root.getFile('log.txt', {create: true, exclusive: true}, function(fileEntry) {
}, errorHandler);
}
The alert(fs) resulted in DOM FileSystem and that means that the fs variable is the FileSystem.
But when I do this:
function initFS()
{
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,function(grantedBytes){
window.requestFileSystem(window.TEMPORARY, grantedBytes, function(filesystem) {
fs = filesystem;
}, errorHandler);
})
}
if (window.requestFileSystem) {
initFS();
}
alert(fs);
the alert(fs) returned null.
Is there any solution that can be done to this? Any explanation would be useful for this.
My last resort would be add a button so that after the click the fs will definitely be a filesystem, but I try to avoid that method.
It's probably because requestQuota and requestFileSystem functions are asynchronous. In other words, the alert() is being executed before fs is set.
So.. you could put all the code in the requestFileSystem callback? I'm unclear on what you are trying to achieve
For example you could do:
function initFS(callback)
{
window.webkitStorageInfo.requestQuota(PERSISTENT,5*1024*1024,function(grantedBytes){
window.requestFileSystem(window.TEMPORARY, grantedBytes, function(filesystem) {
callback(filesystem)
}, errorHandler);
})
}
if (window.requestFileSystem) {
initFS(function (fs) {
alert(fs)
});
}
Related
Ho to everyone. I followed this tutorial to create a modal view with a pdf generated with pdfmake.
http://gonehybrid.com/how-to-create-and-display-a-pdf-file-in-your-ionic-app/
My simply question is how can i save the pdf in my local storage on in cache? I need that to send the pdf by email or open it with openfile2. I'm using Ionic and cordova.
I don't know how you code it, but I know what plugin you should use:
https://github.com/apache/cordova-plugin-file
The git contains a complete documentation of the plugin so everything you could need should be there.
Sample code to write pdf file in device using cordova file and file transfer plugin:
var fileTransfer = new FileTransfer();
if (sessionStorage.platform.toLowerCase() == "android") {
window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
// for iOS
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}
function onError(e) {
navigator.notification.alert("Error : Downloading Failed");
};
function onFileSystemSuccess(fileSystem) {
var entry = "";
if (sessionStorage.platform.toLowerCase() == "android") {
entry = fileSystem;
} else {
entry = fileSystem.root;
}
entry.getDirectory("Cordova", {
create: true,
exclusive: false
}, onGetDirectorySuccess, onGetDirectoryFail);
};
function onGetDirectorySuccess(dir) {
cdr = dir;
dir.getFile(filename, {
create: true,
exclusive: false
}, gotFileEntry, errorHandler);
};
function gotFileEntry(fileEntry) {
// URL in which the pdf is available
var documentUrl = "http://localhost:8080/testapp/test.pdf";
var uri = encodeURI(documentUrl);
fileTransfer.download(uri, cdr.nativeURL + "test.pdf",
function(entry) {
// Logic to open file using file opener plugin
},
function(error) {
navigator.notification.alert(ajaxErrorMsg);
},
false
);
};
I'm currently creating text files with code similar to the following. This will create a file just fine, but it won't delete an existing file.
fs.root.getFile('log.txt', {create: true, exclusive: false},
function(fileentry) {
fileentry.createWriter(function (filewriter) {
filewriter.write('Hello world!');
});
}
);
Any way of deleting an existing file cleanly without too much extra code or dedicated deletion code?
I've been using this guide but with no luck finding an efficient way of doing this.
http://www.html5rocks.com/en/tutorials/file/filesystem/
This is as close as I can get. It checks for the file, removes if it's there. It also captures the error if it cannot be removed. If by the end of all that, there is space for the new file, it is created as before.
fs.root.getFile('log.txt', {create: false},
function(fileentry) {
fileentry.remove(createfile, errorhandler);
},
createfile
);
function createfile(){
//either the file was never there or has been removed successfully
fs.root.getFile('log.txt', {create: true, exclusive: false},
function(fileentry) {
fileentry.createWriter(function (filewriter) {
filewriter.write('Hello world!');
});
}
);
}
function errorhandler(error){
//file already exists and couldn't be removed
}
It's not as compact nor and pretty as I'd have liked, but it's the best I can come up with for now.
This should work much like your writer does:
fs.root.getFile('log.txt', {create: false}, function(fileEntry) {
fileEntry.remove(function() {
console.log('File deleted.');
}, errorHandler);
}, errorHandler);
I am developing intel cordova app...
to download files from server , i have included cordova file download plugin but it has data that i want to pass through variable...
here is my code:
var app = {
fileName: "PointerEventsCordovaPlugin.wmv", //<-- pass this value through variable (dynamic)
uriString: "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv", // <-- this one also
// Application Constructor
initialize: function() {
this.bindEvents();
},
....
I have added fileName and uristring.. but i want to add that value dynamically from variable.. how can i do this?????
cordova plugin link
please if you know anything about this than reply...
Following the example from the link you provided, remove the fileName and uriString fields from the app object, and parameterize the needed functions. For example, startDownload will become:
startDownload: function (fileName, uriString) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getFile(fileName, { create: true }, function (newFile) {
app.downloadFile(uriString, newFile);
});
});
},
I have an MVC 5 view with a form and a plupload file uploader section. Upload is triggered by a button on the form. I have no problem uploading file chunks to the server and setting the parameters to the query string and all, but what I do have a problem with is starting the upload only after a custom sanity check has been performed.
Here's what I have tried:
var uploader = new plupload.Uploader({
runtimes: 'html5',
drop_element: 'upload',
browse_button: 'browse',
url: "../UploadFile",
chunk_size: "1024kb",
multipart_params: { "uid": "uid", "chunk": "chunk", "chunks": "chunks", "name": "name" },
init: {
PostInit: function(file) {
document.getElementById("filelist").innerHTML = "";
document.getElementById('submit-all').onclick = function () {
document.getElementById("infoPopup").style.visibility = "visible";
document.getElementById('submit-all').enabled = false;
var uuid = Math.uuidFast();
document.getElementById("uid").value = uuid;
uploader.settings.multipart_params = { uid: uuid, chunk: file.chunk, chunks: file.chunks, name: file.name };
if (checkReq) {
uploader.start();
}
return false;
};
},
The crucial part here is this:
if(checkReq){
uploader.start();
}
"checkReq" is my custom sanity check script that verifies that form values are not nonsensical (e.g. single form entries might be perfectly valid while in combination they are simply wrong, etc.).
So the above does not prevent the upload, the check script is not even fired, Firebug console output shows no error.
Since googling tells me that there is also a "BeforeUpload" event, I tried this:
BeforeUpload: function(up, file) {
if (checkReq) {
up.stop();
return false;
}
return true;
},
Which also does not seem to fire at all.
Edit: Next attempt, I put the call to my checkReq fuction into BeforeUpload in "preinit", which should fire before any chunking etc is done, so before the upload is prepared. This also failed although I have no idea why it does not fire:
var uploader = new plupload.Uploader({
runtimes: 'html5',
drop_element: 'upload',
browse_button: 'browse',
url: "../UploadFile",
chunk_size: "1024kb",
multipart_params: { "uid": "uid", "chunk": "chunk", "chunks": "chunks", "name": "name" },
preinit: {
BeforeUpload: function (up) {
if (checkReq) {
uploader.stop();
uploader.splice(0, uploader.files.length);
return false;
}
return true;
}
},
init: {
PostInit: function(file) {
...
I had used "dropzone.js" before, and my script worked fine with that but I found that I needed chunked uploads so I had to move to plupload and now my script is being ignored.
Could someone please tell me where I am being stupid here? Thanks!
Got it solved.
It's a nasty, ugly hack, but it works:
Made the "actual" submit/upload button hidden
Made a second button that acts as pre-submit button with onclick function
onclick function calls checkReq and if that returns true, the function calls the click() function of the "actual" submit/upload button
Like I said: nasty but it works.
I was wondering how do I put HTML form user input into a file using JavaScript ONLY.
I have struggled to find an answer to such a simple question.
Writing data to files on a local filesystem is only supported in modern browsers with a set of limitations, you can google for HTML FileSystem API.
As for writing to a file, this is a basic example:
function onInitFs(fs) {
fs.root.getFile('log.txt', {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
fileWriter.write(blob);
}, errorHandler);
}, errorHandler);
}
window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler);