HTML5 read file from IPad document Directory - javascript

I have created html5 based app in Titanium for ipad. Using Titanium I have stored a file named demo.txt in
/Users/anonymous/Library/Developer/CoreSimulator/Devices/FE1CFXXX0AC-D5BD-9615-C58D80B5A9C6/data/Containers/Data/Application/2D25XXXX-4687-B28A-1EA7B7EA3013/Documents/
in same application itself. Now I need to want to access content of demo.txt in my index.html. Anyone having idea regarding this please help me out.

You can use similar technique to read a file:
var pagesDetailFile = Ti.Filesystem.getFile(Titanium.Filesystem.applicationDataDirectory, "demo.txt");
alert(pagesDetailFile.read()); // Read the file
pagesDetailFile = null; // remember to release the file
You should read the documentation carefully for available functions.

You will have to use the techniques described at https://appcelerator.github.io/appc-docs/platform/latest/#!/guide/Communication_Between_WebViews_and_Titanium to fire an event in the WebView HTML which you'd pick up in Titanium JS, get the file and then use evalJS or fireEvent to send it back to the WebView HTML.

I used jquery in order to read data from the simulator and it works for devices too.
var filePath = "/Users/anonymous/Library/Developer/CoreSimulator/Devices/FE1CFXXX0AC-D5BD-9615-C58D80B5A9C6/data/Containers/Data/Application/2D25XXXX-4687-B28A-1EA7B7EA3013/Documents/admin/content.txt";
$.ajax({
url: filePath,
context: document.body,
async: false,
success: function(response){
Ti.API.info("FILE CONTENT " + response);
},
error: function(data){
alert('does not exist');
}
});
filePath is actual path in which we are storing data.

Related

Invalid downloaded file name on MS Edge

I have some problem with MS Edge 20.10240.16384.0 (the newest versions has the same error).
I'm trying to download file with JS (clear JS, I have no opportunity to use any libraries). Here is the way I'm doing this:
window.open(url);
Where url variable is an URL to file which I want to download. Opening that URL instantly causes file download. The problem is that the downloaded file has no extension and it's name looks like
'=_UTF-8_B_dGVzdEZpbGVOYW1lLV9kc2FkLnBkZg==_='
The original file name is 'test.pdf' and my method works perfect with Chrome, Firefox and IE11.
Are there any solutions?
Thanks.
Took me a good few hours and found out that if file name has '£' character, the file gets download as txt with random characters as the file name.
Added code in the API to replace '£' with 'GBP' for the file name.
File download works perfectly fine now.
Weird thing is that I check all characters against Path.InvalidPathChar() list provided with System.IO.File class. Yet '£' throws an error. And that's also why I couldn't get the issue right away as I know '£' is an allowed character.
File download tested with ASP.Net MVC WebApi.
Both IE and Edge keep failing but Chrome and Mozilla works without an issue.
Somehow to fix that error in MS Edge. We can do something stupid like this.
I don't know about the your server's programming language. So I simply post you a flow-chart about it for you to implement it.
Here's a client code:
(I am sorry that I used a library (jQuery))
var uid = "12093ujdskf3";
var url;
$.ajax({
dataType: "json",
url: "http://www.example.com/download.jsp",
data: {
uid: uid
},
error: function(){
url = null;
},
success: function(data){
url = data.url;
}
});
if (url == null){
alert("Error occurred!");
return;
}
window.open(url);

How to read metadata from mp4 using mp4.js node module?

I am trying to read the metadata tags from an mp4 file into my javascript using the node module mp4js. I followed the model provided on that page but with some issue.
I tried the following:
var mp4 = require('mp4js');
mp4({ file: 'small.mp4', type: 'local' }, function (err, tags) {
// tags now contains your MP4 tags
console.log('Tags: ' + tags)
$scope.mp4Tags = tags;
});
and I was met with Uncaught TypeError: Cannot read property 'join' of undefined
Does anyone know what I'm missing here? Could it be that the mp4 doesn't have any tags? I just googled "sample mp4" and downloaded something. It's my first time trying this module and I am pretty new to node.
I'm also open to other suggestions for reading mp4 metadata.
Thank you very much for your time and let me know if you need any additional from me.
EDIT 8.26.2015
Following Brad's suggestion, I tried the following code to read metadata from an mp4:
var child_process = require('child_process');
ls = child_process.spawn('ffmpeg/bin/ffprobe.exe', ['-print_format', 'json', 'out.mp4']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
$scope.mp4data = data;
});
I created mp4.out by following this example for adding a title meta tag using ffmpeg from the command line. Here is a screenshot of my output. Here is the command I entered:
ffmpeg -i in.avi -metadata title="my title" out.flv
After running my app with the code above, the value stored in $scope.mp4data is a Native Buffer that looks like this. All I see are some numbers, but no metadata tags. How can I view the metadata such as the title that I set using the command above? Am I missing something in the arguments? Or maybe I should be looking at something other than data?
Thanks for the help. I may just post this as a new question since the focus has shifted.
EDIT: Solution
Here's where I landed thanks to Brad's help:
$scope.mp4data = "";
ls.stdout.on('data', function (data) {
$scope.mp4data = $scope.mp4data + data.toString();
});
ls.stdout.on('end', function (data) {
$scope.mp4data = JSON.parse($scope.mp4data);
});
works great for reading metadata from my mp4! Thanks Brad!
I recommend using FFprobe (from the FFmpeg project) to do this instead. It supports many containers, including MP4.
You can use ffprobe -print_format json to have it output JSON data that you can parse inside your Node.js app.
Some examples here: https://stackoverflow.com/a/8191228/362536

Why doesn't Microsoft Skydrive download multiple files even though MS example shows it? (wl.download)

Summary
I am attempting to find out why the wl.download function will not download more than one file even though the Microsoft examples seem to indicate that they can.
And, the code seems to be called for each file you attempt to download, but only the one file is actually downloaded.
Details
Here are the details of how you can see this problem which I've tried in IE 11.x and Chrome 30.x
If you will kindly go to :
http://isdk.dev.live.com/dev/isdk/ISDK.aspx?category=scenarioGroup_skyDrive&index=0
You will be able to run an example app which allows you to download files from your skydrive.
Note: the app does require you to allow the app to access your skydrive.
Once you get there you'll see code that looks like this on the right side of the page:
Alter One Value: select:
You need to alter one value: Change the
select: 'single'
to
select: 'multi'
which will allow you to select numerous files to download to your computer. If you do not make that one change then you won't be able to choose more than one file in the File dialog.
Click the Run Button to Start
Next, you'll see a [Run] button to start the app (above the code sample).
Go ahead and click that button.
Pick Files For Download
After that just traverse through your skydrive files and choose more than one in a folder and click the [Open] button. At that point, you will see one of the files actually downloads, and a number of file names are displayed in the bottom (output) section of the example web page.
My Questions
Why is it that the others do not download, even though wl.download is called in the loop, just as the console.log is called in the loop?
Is this a known limitation of the browser?
Is this a known bug in skydrive API?
Is this just a bug in the example code?
The problem here is that the call to wl.download({ "path": file.id + "/content" }) stores some internal state (among other things, the file being downloaded and the current status thereof). By looping over the list of files, that state is in fact overwritten with each call. When I tried downloading three text files at once, it was always the last one that was actually downloaded and never the first two.
The difficulty here is that the downloads are executed in the traditional fashion, whereby the server adds Content-Disposition: attachment to the response headers to force the browser to download the file. Because of this, it is not possible to receive notification of any kind when the download has actually completed, meaning that you can't perform the downloads serially to get around the state problem.
One approach that I thought might work is inspired by this question. According to the documentation, we can get a download link to a file if we append /content?suppress_redirects=true to its id. Using this approach, we can set the src property of an IFrame and download the file that way. This works OK, but it will only force a download for file types that the browser can't natively display (zip files, Exe files, etc.) due to the lack of the Content-Disposition: attachment response header.
The following is what I used in the Interactive Live SDK.
WL.init({ client_id: clientId, redirect_uri: redirectUri });
WL.login({ "scope": "wl.skydrive wl.signin" }).then(
function(response) {
openFromSkyDrive();
},
function(response) {
log("Failed to authenticate.");
}
);
function openFromSkyDrive() {
WL.fileDialog({
mode: 'open',
select: 'multi'
}).then(
function(response) {
log("The following file is being downloaded:");
log("");
var files = response.data.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
log(file.name);
WL.api({
path: file.id + "/content?suppress_redirects=true",
method: "GET"
}).then(
function (response) {
var iframe = document.createElement("iframe");
iframe.src = response.location;
iframe.style.display = "none";
document.body.appendChild(iframe);
},
function (responseFailed) {
log("Error calling API: " + responseFailed.error.message);
}
);
}
},
function(errorResponse) {
log("WL.fileDialog errorResponse = " + JSON.stringify(errorResponse));
}
);
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}
Did you try to bind some events to the WL.download() method? According to the documentation:
The WL.download method accepts only one parameter:
The required path parameter specifies the unique SkyDrive file ID of the file to download.
If the WL.download method call is unsuccessful, you can use its then method's onError parameter to report the error. In this case, the WL.download doesn't support the onSuccess and onProgress parameters. If the WL.download method call is successful, the user experience for actually downloading the files will differ based on the type of web browser in use.
Perhaps you are getting some errors in your log to identify the problem.
For me, one suggestion without having checked the documentation, I can think of the fact that you are not waiting for each download to end. Why not change your loop in such a manner that you call WL.download() only if you know no other download is currently running ( like calling the next WL.download only in the success/complete event ):
WL.download({ "path": file.id + "/content" }).then(
function (response) {
window.console && console.log("File downloaded.");
//call the next WL.download() here <!-----------------
},
function (responseFailed) {
window.console && console.log( "Error downloading file: " + responseFailed.error.message);
}
);

Do we need a web server (like Apache) to access a .json file?

I was trying to read an info.json file, using the jQuery API. Please find the code below, which is part of test.html.
$.getJSON('info.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
The test.html file resides on my local machine and when I try to open it in the browser, the Ajax call is not getting triggered and the info.json file is not read.
Is it not working because I don't have a web server? Or am I doing anything wrong in the code? (I don't see any errors in the Firebug console though).
Thanks in advance.
You will always have to host your site from where you are making AJAX call. Otherwise it will throw this exception.
origin null is not allowed by access-control-allow-origin
Host your page on localhost server and I guess everything will work nicely.
While technically you don't need a web server for this, some of the libraries you use to abstract network access may not work with local files and some browsers don't let local files do a lot, so something like a little test web server for static files would be very useful for your development and testing.
Install a small webserver like http://jetty.codehaus.org/jetty/
easy to install, and small download ;)
By putting your JSON string into a text file and loading it in a iframe, you can extrapolate the data. (Most browsers can load .txt files in iframes.)
var frame = document.createElement("IFRAME"); //Create new iframe
var body = document.body;
frame.onload = function() { //Extrapolate JSON once loaded
data = JSON.parse(frame.contentDocument.documentElement.innerText); //Loads as a global.
body.removeChild(frame); //Removes the frame once no longer necessary.
}
frame.style.display = "none"; //Because the frame will have to be appended to the body.
body.appendChild(frame);
frame.src = "your JSON.txt"; //Select source after the onload function is set.

Change File extension using Jquery

I have some images in a folder with the .JPG extension. I want to change the image extension to .PNG programmatically. My earlier post is here: https://stackoverflow.com/questions/15428521/read-a-file-extension-and-change-that-extension.
$.ajax({
type: "GET",
url: "aa.jpg",
dataType: "snapshot",
success: function (snapshot)
{
try
{
var src = $(this).attr("url");
$(src).attr('src',$(this).attr('url').replace('.jpg','png'));
}
catch(ex)
{
alert(ex);
}
}
});
After reading both your question I realise that you want to rename files on the client.
This cannot be done using jQuery alone. Normal javascript engines do not allow access to filesystems on client side.
You need something a little more powerful - on windows that would be an ActiveX object. If you're on another OS, or a browser which does not support ActiveX, I don't know how to help you.
Here you can find an example.

Categories

Resources