Android - Save Form Data Locally To CSV - javascript

I have a simple Android App using simple js, jquery mobile and phonegap that has form data that I would like to write to CSV on /sdcard. I can not figure out the best way to do this. It needs to write locally to CSV since the device will not have internet access. Each time the form is filed out, each CSV file name must be unique, containing 'CompanyName' field. I have searched everywhere and cannot figure this out. Help Please...

I have implemented similar things (read/write data via mobile web-app with no internet connection).
You might be able to utilize the same approach that I took which is using custom ContentProvider in Android to save your data. Provided the data is not large, this approach should work. If that is the case then you could do the following:
Create custom content URI scheme such as content://myuri. This is a neat feature of Android since I could call this URI from the built-in browser including even using links in your HTML page. It basically treat this URI as any other http:// uri
In the implementation for writing you could devise the URL as content://myuri/writeData/input1=value1/input2=value2/input3=value3 and so on. I am not sure if there is a limitation in ContentProvider for the length of URI accepted by the ContentProvider which is why I put the caveat above. I don't have a large form when I tried this approach last time
In the implementation of your extension of ContentProvider, you need to override the function public ParcelFileDescriptor openFile (Uri uri, String mode) and have them interpret the URI that is given in step #2. The implementation should be parsing the URI and then write the data to the CSV as you intended
You can get this data back using different URI scheme such as content://myuri/getData/[theFileID] which now in the implementation of #3 above, you will do the reverse and return the CSV data to your mobile web-app
Let me know if you have any question.

Related

Drag File in Data URI format from Browser to Desktop

As this blog post points out, there is a way to download files via drag and drop from browser to desktop.
I want to drag a file in data uri format (e.g. "data:application/octet-stream;base64,eNcoDEdFiLEStuFf") to the desktop. I cannot provide a full URL to a server download due to security reasons (file needs to be handled clientside).
When I try what's given in the example of the blog post, a file which content and name is the current timestamp is created:
item.addEventListener("dragstart", function(evt) {
evt.dataTransfer.setData("DownloadURL", "data:application/octet-stream;base64,eNcoDEdFiLEStuFf");
}
I already tried changing the format parameter, tweaking the format of the data a little and deconding beforehand but nothing works, I never get any of my data onto my desktop. Is there any way to accomplish what I am looking for, at least in some browsers?
By the way, we do not use jQuery. As a result, it might be interesting if there is a solution with jQuery but this will most probably not be applicable for our project.
As far i understood download URL should have following format:
mime-type:file_name:URL. Were URL is your data URI.
For your case:
item.addEventListener("dragstart", function(evt) {
evt.dataTransfer.setData("DownloadURL", "application/octet-stream:fileName.bin:data:application/octet-stream;base64,eNcoDEdFiLEStuFf");
}
Which should create fileName.bin file.
Take a look at http://jsfiddle.net/Andrei_Yanovich/jqym7wdh/
But it looks like it works only in chrome

how to secure img src path when user clicks on view source using javascript?

How to secure the src path of the image when clicks on inspect element so that user should not get to know about the actual src path..please help me with the solution and it should be done with javascript only no other tags should be used.
You can convert image into base 64 data URIs for embedding images.
Use: http://websemantics.co.uk/online_tools/image_to_data_uri_convertor/
Code sample:
.sprite {
background-image:url(data:image/png;base64,iVBORw0KGgoAAAA... etc );
}
This is commonly done server-side, where you have an endpoint that serves the image file to you as bytes...
You can store the images in a private location on the server where IIS/<your favourite web server> doesn't have direct access to it, but only a web app, running on it, with the required privilege is authorized to do so.
Alternatively people also "store" the images in the database itself and load it directly from there.
In either case, the response which has to be sent back has to be a stream of bytes with the correct mime type.
Edit:
Here are a couple of links to get you started if you are into ASP.NET:
http://www.codeproject.com/Articles/34084/Generic-Image-Handler-Using-IHttpHandler
http://aspalliance.com/1322_Displaying_Images_in_ASPNET_Using_HttpHandlers.5 <- this sample actually does it from a database.
Don't let the choice of front-end framework (asp.net, php, django, etc) hinder you. Search for similar techniques in your framework of choice.
Edit:
Another way if you think html5 canvas is shown here: http://www.html5canvastutorials.com/tutorials/html5-canvas-images/
However you run into the same problem. Someone can view the image url if they can see the page source. You'll have to revert to the above approach eventually.

How best to export a grid to PDF in ASP.NET MVC

I don't know that this is necessarily important, but I'm using Infragistics iggrid for my grid and their Reports stuff to export to PDF.
The underlying issue I have is that my data that I want to export is in the browser and I would prefer that I don't have to create a server-side file to download. We have an icon on the screen that the user clicks to download the PDF.
So what I'm doing on the client, is collecting all the data. This has to be done client-side because I want to export the data as the user has it sorted, filtered, and column-ordered (otherwise I could just collect the data server-side which would make this simpler). I then send the data to the server via a POST.
On the server-side I generate the PDF file. Now, obviously, I could save the PDF server-side and redirect to the generated file, but that adds maintenance of temporary files which I'd prefer to avoid (but worst case, I can go there. Just fishing for options right now).
I tried returning the data base64 encoded and then doing:
window.open("data:application/pdf;base64," + encodedData);
This doesn't work (at least in IE) because the URL limit is a bit over 2K.
I tried using the downloadDataURI javascript function here: http://code.google.com/p/download-data-uri/
But that only appears to work with Chrome (even after commenting out the webkit check) and I'm apparently not clever enough to figure out why.
I'm sure I'm missing some obvious possibility that doesn't require creating a server-side file, but I'm just not seeing it. (disclaimer: My daughter woke me up horribly early this morning so the answer could be really trivial and I will feel stupid tomorrow when my brain is working).
On the server-side I generate the PDF file. Now, obviously, I could
save the PDF server-side and redirect to the generated file, but that
adds maintenance of temporary files which I'd prefer to avoid (but
worst case, I can go there. Just fishing for options right now).
You don't need to save it on the server. You can simply stream the PDF File (I assume you have it in some sort of Stream or byte[]) to the user. All you need to do is something like
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "filename.pdf");
Response.BinaryWrite(bytes);
Response.Flush();
Response.Close();
Response.End();
And this will prompt the user to either save the file or open it in Adobe Reader. The file won't be created on the server at all.

Save XML file on my machine with XMLDom object save()

I'm not able to save to the xml file on my machine.
I have noticed that node value is changed temprorily but not permanent in xml file.
P.S : This is only a simple HTML file with javascript
It is giving me an error "Permission Denied"
function viewBookDetails() {
var xmlDoc = xmlLoader("cart.xml");
//var x = xmlDoc.getElementsByTagName("dogHouse")[0];
var x = xmlDoc.documentElement;
var newel = xmlDoc.createElement("essy");
x.appendChild(newel);
alert(x.xml);
xmlDoc.save("cart.xml");
}
is it not possible to save xml file on my machine?
Thank you,
In general, browser JavaScript has no I/O API and cannot read or write to the client filesystem since that could be a security loophole. I haven't seen or used the save() method before but it looks like it's an IE specific extension to the XML DOM. If you must use it, this thread might provide the solution, the answer that worked for the OP there suggested:
I haven't proofed your code but here is something you might want to try. I am taking a shot in the dark that you are using this on a Windows OS since you are using IE and from the sound of the error. Just take your html file that you have and rename it the whatever.hta and it will then be able to write to the xml file and save.
Also, the documentation for the method says the following for when the argument is a string (as in your code snippet):
String
Specifies the file name. This must be a file name rather than a URL. The file is created, if necessary, and the contents are replaced entirely with the contents of the saved document. This mode is not intended for use from a secure client, such as Microsoft Internet Explorer.
From the forum posts (links below) that deal with the same issue, I gleaned the following:
This is an IE specific extension and so will only work in IE
There are obviously security restrictions in place so you shouldn't be able to do this 'out of the box'
One workaround that crops up often is to rename the file extension to .hta (Hypertext Application) instead of .html
I'm not sure but there might also be some workarounds by changing the permissions for the security zones your application runs in
References:
http://www.codingforums.com/showthread.php?t=25048
http://p2p.wrox.com/xml/4053-error-using-xml-save-method.html
http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/204995

Generate some xml in javascript, prompt user to save it

I'd like to make an XML document in JavaScript then have a save dialog appear.
It's OK if they have to click before the save can occur.
It's *not* OK if I *have* to use IE to achieve this (I don't even need to support it at all). However, Windows is a required platform (so Firefox or Chrome are the preferred browsers if I can only do this in one browser).
It's *not* OK if I need a web server. But conversely, I don't want to require the JavaScript to be run on a local file only, i.e. elevated privileges -- if possible. That is, I'd like to to run locally or on a *static* host. But just locally is OK.
It's OK to have to bend over backwards to do this. The file won't be very big, but internet access might either be there, be spotty or just not be a possibility at all -- see (3).
So far the only ideas I have seen are to save the XML to an iframe and save that document -- but it seems that you can only do this in IE? Also, that I could construct a data URI and place that in a link. My fear here is that it will just open the XML file in the window, rather than prompt the user to save it.
I know that if I require the JavaScript to be local, I can raise privileges and just directly save the file (or hopefully cause a save dialog box to appear). However, I'd much prefer a solution where I do not require raised privileges (even a Firefox 3.6 only solution).
I apologize if this offends anyone's sensibilities (for example, not supporting every browser). I basically want to write an offline application and Javascript/HTML/CSS seem to be the best candidate considering the complexity of the requirements and the time available. However, I have this single requirement of being able to save data that must be overcome before I can choose this line of development.
How about this downloadify script?
Which is based on Flash and jQuery, which can prompt you dialog box to save file in your computer.
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
Using a base64 encoded data URI, this is possible with only html & js. What you can do is encode the data that you want to save (in your case, a string of XML data) into base64, using a js library like jquery-base64 by carlo. Then put the encoded string into a link, and add your link to the DOM.
Example using the library I mentioned (as well as jquery):
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
//include jquery and jquery-base64 here (or whatever library you want to use)
document.write('click to make save dialog');
</script>
</body>
</html>
...and remember to make the content-type something like application/octet-stream so the browser doesn't try to open it.
Warning: some older IE versions don't support base64, but you said that didn't matter, so this should work fine for you.
Without any more insight into your specific requirements, I would not recommend a pure Javascript/HTML solution. From a user perspective you would probably get the best results writing a native application. However if it will be faster to use Javascript/HTML, I recommend using a local application hosting a lightweight web server to serve up your content. That way you can cleanly handle the file saving server-side while focusing the bulk of your effort on the front-end application.
You can code up a web server in - for example - Python or Ruby using very few lines of code and without 3rd party libraries. For example, see:
Making a simple web server in python
WEBrick - Writing a custom servlet
python-trick-really-little-http-server - This one is really simple, and will easily let you server up all of your HTML/CSS/JS files:
"""
Serves files out of its current directory.
Doesn't handle POST requests.
"""
import SocketServer
import SimpleHTTPServer
PORT = 8080
def move():
""" sample function to be called via a URL"""
return 'hi'
class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
#Sample values in self for URL: http://localhost:8080/jsxmlrpc-0.3/
#self.path '/jsxmlrpc-0.3/'
#self.raw_requestline 'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
#self.client_address ('127.0.0.1', 3727)
if self.path=='/move':
#This URL will trigger our sample function and send what it returns back to the browser
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(move()) #call sample function here
return
else:
#serve files, and directory listings by following self.path from
#current working directory
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)
print "serving at port", PORT
httpd.serve_forever()
Finally - Depending on who will be using your application, you also have the option of compiling a Python program into a Frozen Binary so the end user does not have to have Python installed on their machine.
Javascript is not allowed to write to a local machine. Your question is similar to this one.
I suggest creating a simple desktop app.
Is localhost PHP server ok? Web traditionally can't save to hard drive because of security concerns. PHP can push files though it requires a server.
Print to PDF plugins are available for available for all browsers. Install once, print to PDF forever. Then, you can use a javascript or Flash to call a Print function.
Also, if you are developing for an environment where internet access is spotty, conwider using VB.NET or some other desktop language.
EDIT:
You can use the browser's Print function.
Are you looking for something like this?
If PHP is ok, if would be much easier.
With IE you could use document.execCommand, but I note that IE is not an option.
Here's something that looks like it might help, although it will not prompt with SaveAs dialog, https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FOL.
One simple but odd way to do this that doesn't require any Flash is to create an <a/> with a data URI for its href. This even has pretty good cross-browser support, although for IE it must be at least version 8 and the URI must be < 32k. It looks like someone else on SO has more to say on the topic.
Why not use a hybrid flash for client and some server solution server-side. Most people have flash so you can default to client side to conserve resources on the server.

Categories