Ajax/Javascript - File Download - javascript

Client (Request through XMLHttpRequest) -> Server.
Server [Builds CSV and prints it on the output stream of response] -> Client.
Now step 3 should be-> Client's browser should show a download dialogue (save, open and cancel). Since the content type is plain text from the server, and the content disposition is not set, can we create a file using javascript and prompt the user to download?
I know this question is slight stupid. But there is no other option. I have to do it this way.
Changing in the server side script will make it a one minute task. But I have to do it in the client side. The responseText property of the XMLHttpRequest object will be plain text and I have to show download prompt for the text file.
Is this possible?

Not that I'm aware of. But you could just use location.href (or a form, if POST data is needed) to request the server-side file. With the correct headers (Content-Disposition: attachment and I think there's another one) you can have the response be downloaded rather than displayed.
EDIT: Even better, use an iframe that's hidden. That way, you can still do a fancy "Loading, please wait" thing in the main page.

Theoretically it could be possible, by using Data URI's
<a download = "yourfile.csv" href="data:application/octet-stream;charset=YOURCHARSET;base64,BASE64allthedata">Generate</a>

Related

How Can I make my browser show files (images) that a server is sending me with download prompt?

The only solution I've found it to grab the link with getElementsByClassName then inject it into an html snippet on the page, but it looks so fake, and is also unnecessary (I don't want all the links)
I want to right click the link (one at a time) and show it to the next tab. If I right click the link the server sends me a download prompt. How can I evade this?
I think the browser decides to download a file or display it based on its MIME type.
If the server is under your control, you should make sure you supply the correct Content-Type HTTP header (e.g. you have to call a library function in PHP, and there should be a similar way to do that in other languages).
Otherwise, for a purely client-side solution in JavaScript, you can fetch the file with an XMLHttpRequest (most JavaScript toolkits have wrappers around it). Then, you can convert it to base 64, prefix the result data:image/png;base64,, and use it as the src attribute of an img element (thanks https://stackoverflow.com/a/21508186/324969).
Note that for security aspects, grabbing arbitrary files and stuffing them in a data: URL might not be safe. I don't know if any cross-site scripting or CORS attacks could be built upon this. You'll have to ask a separate question to know if the client-side solution is unsafe. For the server-side, be careful not to set the wrong content-type for user-uploaded data, or for endpoints of your service (e.g. letting the client-side send you in the request the Content-Type that it would like, as tempting as it looks, is a big no-no).
To open the image in a new tab, you can use window.open as usual, but download the image beforehand (using XMLHttpRequest) and put the data:image/png;base64,… as the URL of the new tab.
Since you can already see the images by placing their URL in an img tag, you can paint that img on a , extract a PNG from the canvas, craft a data:image/png;base64,… URL from that, and then either automatically open many tabs with these URLS, or write in your page a series of links to data: URLs.
You could also have a link to a tiny web page with just the img tag that you currently use: link text.

Workaround for Error 414 when opening file from PHP script

I have a PHP script that's outputting a CSV file and up until now I've been just using a link and passing parameters that are used to determine the output in the GET data. However recently the size of the data increased and now that code gets Error 414 - Request URI too Large. I tried using a hidden form to do it with POST but it just reloaded the page and didn't supply a prompt to download the file and all of the suggestions I've been able to find online about doing it with AJAX suggest using a link with GET data instead. Does anyone know a workaround that will have the browser still let the user easily download the data?
Presently I'm just setting the href attribute of a <a> tag.
$("#exportCSV").attr('href', "myscript.php/?data=" + exportData);
exportData has become too long for GET data but I want to maintain the behavior where if you click on a link that has say a CSV file being outputted the browser provides a download dialog for the user.

getJSON only responds to plaintext and will not work otherwise?

I am using $getJSON to pull down a JSON string from a link (e.g. /login?user=foo&pass=bar). When I plug this link straight into the browser I get a "File Download" prompt ("which is a: application/json"). getJSON does NOT work on that link.
However! When I open the file in the "file download" prompt in notepad and host that text onto my server as just plain text (.txt file) and call getJSON on THAT link (i.e /jsondata.txt), it works perfectly.
Keep in mind I don't have the ability to change anything on the back end.
Any idea what is going on here? Basically I can pull down the JSON file when I host it as plain text but not as it is returned by default.
EDIT
Here's my code...pretty straightforward:
$.getJSON("http://EXTERNALHOSTNAME.com/WEBSERVICE.svc/login?username="+document.frmLogin.email.value+"&password="+document.frmLogin.password.value+"", function(data) {
alert("it worked!");
});
if I replace that line with a link to a dropbox .txt file, it works:
//$.getJSON("http://dl.dropbox.com/u/NUMBERS/login.txt", function(data) {
You can't call other domains (other than originating domain) from javascript. If EXTERNALHOSTNAME supports jsonp responses, you can solve your problem with ading &callback=? to your query. If not you can put a script on your server that will route that response, so that it appears as originating from your own domain. Other than that, if you can serve pages from EXTERNALHOSTNAME (which I doubt) you can serve an iframe from that domain that executes this ajax call (so that it doesn't violate same origin rule), and then smuggle that data to parent frame.

How to send an image from desktop(client) to server & vice versa

I have a web page, by clicking on a Button
a file browser dialog box opens (it should be able to access the client's system)
choose a jpg/gif/any image file and click OK to send
send it to server via AJAX
once the image saved in server, a confirm message appears and
save image populated on client machine in dialog/another window
No. 3, 4 can do using Ajax and server side programmimg (java), but i am not very confident about 1, 2 & 5.
Please help...
Thanks in advance
1 & 2 Use an HTML input tag of type file: <input type='file' id='uploadfile'>. Alternativly if you don't mind using a little flash Uploadify is pretty cool. I', not sure what you mean by step 5. Do you want the uploaded image to be displayed somewhere on the active browser window?
A standard file input.
Better validate filetype on the server not client. You may use accept attribute, but there's no use from it in most browsers.
Use ajaxupload
Send ajax response and handle it on the client side. Display the image in img, for example.
Not sure. Why do you want to save it when the user just uploaded it from his machine?

how to download client side content

I want to let the user download the current content of a textarea into a text file on their computer. In the past I would create an iframe pointing to a URL with the data, which would trigger a file download dialog. However this time the data is client side.
So, is it possible to let the user download data without sending it server side?
If it does not need to work in "old browsers" like IE, you could open a new window with the location 'data:text/plain,' + yourTextarea.value. The user can then save that file using the File/Page menu or Ctrl+S.
is it possible to let the user download data without sending it server side?
In the general case no.
It is possible with a data: URL, as in janmoesen's answer (although you should be URL-encoding the value to include in the URL, or you may face corruption when a %nn sequence appears in the data).
However, this becomes impractical for very long data, and it's not available in old browsers or IE. (IE8 allows short data URLs to be used for images, but not direct navigation.) So whilst you can include a data-URL method to enhance the process on browsers that support it, you will still need a fallback solution of sending a formful of the data to the server side and having it spit back a file in response.
(For security reasons, this should only be allowed in a POST request, and the server should include Content-Disposition: attachment in the response. A content-echo script can give you cross-site-scripting problems otherwise.)
Check out how File and Blob types work.
You can create one and trigger a download programmaticaly:
https://www.bennadel.com/blog/3472-downloading-text-using-blobs-url-createobjecturl-and-the-anchor-download-attribute-in-javascript.htm
https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/

Categories

Resources