How to access audio fle and upload to server in phonegap - javascript

i have one query like i want access to all audio file in phone gap ios and want to upload to server, so any one know how to do get all mp3 files and get upload.
we should need to create a plugin for that .

I don't think you require to create a new plugin. The existing File and File Transfer API should work in your case unless you have more requirements other than the ones stated here.
Use the file API to iterate over all the files in the app.
function success(entries) {
var i;
for (i=0; i<entries.length; i++) {
console.log(entries[i].name);
//Check if the file is in mp3 format. If it is in mp3 format, trigger file upload.
}
}
function fail(error) {
alert("Failed to list directory contents: " + error.code);
}
// Get a directory reader
var directoryReader = dirEntry.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(success,fail);
Then use the file upload API to upload the files to the server.
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);

Related

How do I open and display a base64 pdf from inside my Cordova App?

I am creating an App for Android using Cordova, and I would like to open and display a file (PDF or image) that is served from the server as Base64-encoded binary data.
Of course I have read the multiple other posts on the subject that already exist on this website, but none of the proposed solutions have worked for me, more details below.
To be more precise, the server sends a JSON-file to the app, which among many other things contains a string consisting of the base64-encoded contents of a PDF file. I want to convert this data back into the represented PDF and display it to the user.
If this were a pure browser page, I would simply package my base64 data into a data-URL, attach this as the href of some anchor, and add a download-attribute. Optionally I could wrap all of my data into a blob and create an object url for that first.
In Cordova, this does not work. Clicking the <a> does nothing. Here is what I have attempted so far:
Using the file plugin, I can write the binary data to a file on the device. This works, and using a terminal I can see that the file was downloaded correctly, but into an app-private directory which I cannot access normally (e.g. through the file explorer).
Accessing the user's "downloads" folder is blocked by the file system
Using window.open with the file path as the first argument and "_system" as the target does nothing. There is no error but also nothing happens. Setting the target to "_blank" instead, I get an error saying ACCESS_DENIED.
Using cordova.InAppBrowser behaves the same was as window.open
With the plugin file-opener2 installed, the app will not compile, because the plugin is looking for an android4 toolchain, and I am building for android 9 and up
The plugin document-viewer (restricting to PDFs for the time being) suffers the same problem and does not compile.
Passing the data-URI to window.open (or cordova.InAppBrowser) directly loads for a very long time and eventually tells me that the desired page could not be loaded.
The PDF file I am using for testing is roughly 17kb after converting to base64. I know this is technically above the spec for how long data-URIs can be, but Chrome in the browser has no trouble with it whatsoever, and using a much shorter URI (only a few dozen bytes) produces the same behavior.
Ideally, what I would like to do, is download the file and then trigger the user's standard browser to open the file itself. That was, I would not have to deal with MIME types and also it would look exactly how the user expected from their own device.
Alternatively, if that doesn't work, I would be ok with downloading the file into a system-wide directory and prompting the user to open it themselves. This is not optimal, but I would be able to swallow that pill.
And lastly, if there is a plugin or some other solution that solves the problem amazingly, but for PDFs only, then I can also work out something else for images (e.g. embedding a new into my app and assigning the URI to that).
I would be thankful for any suggestion you might have on how to solve this problem. The code I use to download the file currently is shown below.
Thank you for your time.
var filePath = cordova.file.externalDataDirectory; // Note: documentsDirectory is set to "" by Cordova, so I cannot use that
var fileName = "someFileName.pdf";
var mime = "application/pdf";
var dataBlob = /* some blob containing the binary data for a PDF */
function writeFile(fileEntry, dataBlob) {
// Create a FileWriter object for our FileEntry.
// This code is taken directly from the cordova-plugin-file documentation
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
fileWriter.write(dataBlob);
});
}
window.resolveLocalFileSystemURL(
filePath,
function onResolveSuccess (dirEntry) {
dirEntry.getFile(
fileName,
{ create: true },
function onGetFileSuccess (file) (
writeFile(file, dataBlob);
// At this point, the file has been downloaded successfully
window.open(file.toURL(), "_system"); // This line does nothing, and I don't understand why.
}
);
}
);
I managed to solve the problem.
As per the documentation of the file-opener2 plugin, you need to also add the androidx-adapter plugin to correct for the outdated (android 4) packages. With the plugins file, file-opener2 and androidx-adapter installed, the complete code is the following:
var filePath = cordova.file.externalDataDirectory; // Note: documentsDirectory is set to "" by Cordova, so I cannot use that
var fileName = "someFileName.pdf";
var mime = "application/pdf";
var dataBlob = /* some blob containing the binary data for a PDF */
function writeFile(fileEntry, dataBlob) {
// Create a FileWriter object for our FileEntry.
// This code is taken directly from the cordova-plugin-file documentation
fileEntry.createWriter(function (fileWriter) {
fileWriter.onwriteend = function() {
console.log("Successful file write...");
readFile(fileEntry);
};
fileWriter.onerror = function (e) {
console.log("Failed file write: " + e.toString());
};
fileWriter.write(dataBlob);
});
}
window.resolveLocalFileSystemURL(
filePath,
function onResolveSuccess (dirEntry) {
dirEntry.getFile(
fileName,
{ create: true },
function onGetFileSuccess (file) (
writeFile(file, dataBlob);
// At this point, the file has been downloaded successfully
cordova.plugins.fileOpener2.open(
    filepath + filename,
    mime,
    {
     error : function(){ },
success : function(){ }
    }
);
}
);
}
);

Troubles downloading a pdf from PHP and getting it with AngularJS

I hope you're good!
I have an REST-API with PHP (Flight-PHP as framework) running in one server and I want to download a PDF saved in the server. But I'm having troubles with that.
The API resource that needs to be called to download the PDF is like:
GET /sales/:id/download
If I run the resource mentioned above in a browser, it will download a PDF file and it will display the PDF downloaded without troubles.
Now, in the frontend (a.k.a. a web application running in my browser) I have the following code:
$scope.download = (function (id) {
$http.get($rootScope.api_url + 'sales/' + id + '/download')
.then(function (response) {
var resp = response.data;
var blob = new Blob([resp], {type : 'application/pdf'});
saveAs(blob, folio + ".pdf"); //yup, I'm using SaveAs.js
}, function (reason) {
alert("The file weren't downloaded");
});
});
The code mentioned above downloads me a pdf file... But it is white!
So, after open both PDF's (one generated from the backend and another generated from the js script) it appears me with some chars I can't read (literally, I can't read)
So, my question is, how can I download the file using a different encode? And, which is the better way to encode this file to avoid the loss of chars?

How to write into a file (in user directory) using JavaScript?

I want to write text into any file from Chrome (all version) using HTML5 and JavaScript or jQuery.
I have tried using the FileSystem API:
function onFs(fs) {
console.log('test');
fs.root.getFile('log.txt', {create: true, exclusive: true},
function(fileEntry) {
// fileEntry.isFile === true
// fileEntry.name == 'log.txt'
// fileEntry.fullPath == '/log.txt'
fileEntry.getMetaData(function(md) {
console.log(md.modificationTime.toDateString());
}, onError);
},
onError
);
}
window.webkitRequestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, onFs);
But it's not working.
Is there any way to write into the file?
I want to write file in user directory
You cannot directly write file to user filesystem .
After searching SO for similar Questions to accurately resolve Question, was able to $ cat contents of file created at plnkr following this answer posted by #Iain at Where does PERSISTENT file system storage store with chrome? . The file was written to the user filesystem at ~/.config/[chrome, chromium] directory.
Used file manager to navigate to
~/.config/[chrome, chromium]/Default/File System
to review the directory; the file containing text written below, was found in a folder having two digits as a folder name, then within two further sub-directories; a sub-directory having a single lowercase letter as folder name; within this sub-directory there was another sub-directory having two digits as a folder name; the file that was written by window.webkitRequestFileSystem had eight digits as a file name, without an extension, though having correct "text/plain" MIME type; set at Blob type property.
Then at terminal
$ cd ~/.config/[chrome, chromium]/Default/File\ System/[three digits]/[lowercase letter]/[two digits]
$ cat [eight digits]
Lorem Ipsum
Have not tried to create a .sh file and execute it. Would probably require placing the directory in path or moving the file to a folder in existing path; set appropriate permissions for file. Could possibly adjust this at chrome / chromium browser settings, though have not tried this either.
You could probably write a command to copy or move the file at /path/to/file to an folder in path, and execute the file; or other approach.
You can use download attribute of a element to allow download of file created by createWriter to user filesystem.
The file system is sandboxed
Because the file system is sandboxed, a web app cannot access another
app's files. You also cannot read or write files to an arbitrary
folder (for example, My Pictures and My Documents) on the user's hard
drive.
see also at Definititons
persistent storage Persistent storage is storage that stays in the browser unless the user expunges it or the app deletes it.
temporary storage Transient storage is available to any web app. It is automatic and does not need to be requested, but the browser can
delete the storage without warning.
I want to write file in user directory because it has to be user
understandable.
Edit, Updated
You can use the method described above. That is, use a file manager at to review how the folders and files appear in
~/.config/[chrome, chromium]/Default/File System
## do stuff with contents of file written by `window.requestFilesystem`
To view file in chrome / chromium FileSystem you can navigate to DevTools -> Experiments -> check FileSystem inspection , log.txt should be listed at Resources tab at FileSystem .
Can also navigate to file at address bar using URL
filesystem:http://run.plnkr.co/temporary/log.txt
which should have contents
Lorem Ipsum
or
filesystem:http://run.plnkr.co/temporary/
to view all files and directories in root of temporary filesystem
See Exploring the FileSystem API
First launch chrome / chromium with --allow-file-access-from-files flag , see How do I make the Google Chrome flag "--allow-file-access-from-files" permanent? .
Next
window.requestFileSystem = window.requestFileSystem
|| window.webkitRequestFileSystem;
add error handling
function errorHandler(e) {
var msg = '';
switch (e.message) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR';
break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR';
break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR';
break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR';
break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR';
break;
default:
msg = 'Unknown Error';
break;
};
console.log('Error: ' + msg);
}
You should then be able to
function writeFile(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.');
// call `readFile` here
window.requestFileSystem(window.TEMPORARY, 1024*1024, readFile, errorHandler);
};
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, writeFile, errorHandler);
function readFile(fs) {
fs.root.getFile('log.txt', {}, function(fileEntry) {
// Get a File object representing the file,
// then use FileReader to read its contents.
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
console.log(e.target.result)
};
reader.readAsText(file);
}, errorHandler);
}, errorHandler);
}
plnkr http://plnkr.co/edit/EVVNYYUvHiM545T06kMC?p=preview
Note, at Chrome 38+ it is also possible to create a File object using the new File() constructor; see Chrome: Create file input from blob with Javascript? .
No, It is background process, save the data into the file exist in
folder.
This approach, too, will not automatically write created file to an existing folder at user filesystem.
With either approach user action should be required to save file to user filesystem. This can be achieved using download attribute at a element , data URI How to export JavaScript array info to csv (on client side)? , or an iframe element Download File Using Javascript/jQuery ; which should prompt user to either select to save file or not save file.
See also The FileSaver interface , FileSaver.js

Filesystem API - Upload from local drive to local filesystem

Ive read a lot about the filesystem API and HTML5, but i just couldn't find a working solution so i ask you guys:
I want to have a file upload form, drag drop or regular input box doesnt matter, however i want to select a file, and after uploading it should take the file or a whole folder and "upload" it to the filesystem located on the clients computer. The upload is in brackets because i actually want to copy the file/folder to the clients local file system.
Is it even possible? Because i want to make an application, where a user can upload his files such as music or large videos and movies to his local filesystem and edit/watch etc them in my application. I know i have to upload those big files i have to cut them into pieces and load them stacked up, but i just want to start little :)
Thanks in advance
There's indeed little information on this subject at the moment, so I put together an example that combines:
Using the webkitdirectory attribute on <input type="file">.
This allows the user to select a directory using an appropriate dialog box.
Using the Filesystem API.
This is about the sandboxed filesystem which allows you to store files on the client's machine.
Using the File API.
This is the API that allows you to read files. The files are accessible through an <input type="file"> element, through a transfer using drag and drop, or through the Filesystem API.
As these are currently only working nicely in Chrome, I used the webkit prefix where necessary.
http://jsfiddle.net/zLna6/3/
The code itself has comments which I hope are clear:
var fs,
err = function(e) {
throw e;
};
// request the sandboxed filesystem
webkitRequestFileSystem(
window.TEMPORARY,
5 * 1024 * 1024,
function(_fs) {
fs = _fs;
},
err
);
// when a directory is selected
$(":file").on("change", function() {
$("ul").empty();
// the selected files
var files = this.files;
if(!files) return;
// this function copies the file into the sandboxed filesystem
function save(i) {
var file = files[i];
var text = file ? file.name : "Done!";
// show the filename in the list
$("<li>").text(text).appendTo("ul");
if(!file) return;
// create a sandboxed file
fs.root.getFile(
file.name,
{ create: true },
function(fileEntry) {
// create a writer that can put data in the file
fileEntry.createWriter(function(writer) {
writer.onwriteend = function() {
// when done, continue to the next file
save(i + 1);
};
writer.onerror = err;
// this will read the contents of the current file
var fr = new FileReader;
fr.onloadend = function() {
// create a blob as that's what the
// file writer wants
var builder = new WebKitBlobBuilder;
builder.append(fr.result);
writer.write(builder.getBlob());
};
fr.onerror = err;
fr.readAsArrayBuffer(file);
}, err);
},
err
);
}
save(0);
});
$("ul").on("click", "li:not(:last)", function() {
// get the entry with this filename from the sandboxed filesystem
fs.root.getFile($(this).text(), {}, function(fileEntry) {
// get the file from the entry
fileEntry.file(function(file) {
// this will read the contents of the sandboxed file
var fr = new FileReader;
fr.onloadend = function() {
// log part of it
console.log(fr.result.slice(0, 100));
};
fr.readAsBinaryString(file);
});
}, err);
});
That is not possible, exactly, but your app can still probably work. Reading the file is possible through a file input form element, but writing the file back to disk is where you'll run into trouble.
The two ways your browser can write to disk are 1) downloading a file and 2) the HTML5 filesystem API. Option #1 obviously doesn't let your application choose the destination and option #2 only works with browser-created sandbox filesystems. That restriction might not be a deal-breaker for you -- it just means that the folders that your app uses will be buried somewhere in your browser's data files.
Also, the Filesystem API is currently Chrome-only (but it is an open standard). If you want cross-platform support, maybe you can use IndexedDB. You could use localStorage, but Chrome has a hard 5MB limit, which would be terrible for a media application.

Javascript previews with new FileReader API and DataURLs seem inefficient

I am using the new FileReader API to preview images before upload. This is done using DataURLs. But DataURLs can be massive if the images are large. This is especially a problem for me as the user may upload multiple images at a time and previewing the bunch has actually slowed my browser considerably and actually crashed chrome a few times.
Is there any alternative to using DataURLs for previewing images on the client before upload?
You can also store data on the client's disk (in another location so that you can access the file using JavaScript). This article is quite extensive when it comes to this subject:
http://www.html5rocks.com/en/tutorials/file/filesystem/
It's not supported on all browsers though.
You have to request storage space (the file system), then create a file, write data to it, and finally fetch the URL:
window.requestFileSystem(window.PERSISTENT, 5*1024*1024, function(fs) {
fs.root.getFile(filename, {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var arr = new Uint8Array(data.length);
// fill arr with image byte data here
var builder = new BlobBuilder();
builder.append(arr.buffer);
var blob = builder.getBlob();
fileWriter.write(blob);
location.href = fileEntry.toURL(); // navigate to file. The URL does not contain the data but only the path and filename.
});
});
}, function() {});

Categories

Resources