how to download client side content - javascript

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/

Related

How to display a PDF without downloading

I have a PDF like like this:
"http://centraldata.s3.amazonaws.com/.....pdf?AWSAccessKeyId=...."
which I get from an api call. Then I pass it into an link so that users can click and download it.
<a href={pdfUrl} />
So, my question is, is there a way to let user view the PDF without downloading it? Except passing the Url into an tag, I don't know if there is any other way to use this link
When you place a page of HTML in the Public Domain (World Wide Web) you are offering a service with Dis-positions (Download to later view this page after decoding download).
If you include images, text, audio, video or even a PDF via link, then you are offering to disposition a copy of the page content (be dispossessed of all with its content) from the server to the browser.
A web site can indicate to the browser that the download need not be viewed in the browser, (many browsers do not have a PDF viewer, or the browser may be secured to a safer setting such as Download Media ONLY) the HTTP response could include the html attachment headers:
Content-Type: application/pdf
Content-Disposition: attachment; filename="file.pdf"
A web site can indicate to the browser that the download need not be viewed in the browser, but there is a possibility if the user settings allow for inline viewing, (many browsers do not have a PDF viewer or it may be secured to a safer setting such as Download ONLY) the HTTP response should include the html attachment headers:
Content-Type: application/pdf
Content-Disposition: inline; filename="file.pdf"
To avoid problems with the text parsing of the optional filename (blob: or anything will be saved to filename at the discretion of the client dispossesser) then the proffered optional filename should be "double quoted".
User security settings should ideally be set to no-popups, like blanks, open secondary windows or target tabs, since those are unfriendly, anti-social server actions.
W3 Recommendation says
< a href="download-file.pdf" download >right click here for your options including view now< /a>
If you as my client have an inline PDF viewer active, here is an iframe should you wish to use it. (Your servant)
The next two related questions are
How can I stop that content I duplicated, from being duplicated as a copy by the client?, well clearly you cannot, since you willingly gave it away and once decrypted and decoded by the receiver it belongs to them as editable dis possessed content.
How can I mask the source URL ?, generally you can not since to decode the whole file and maintain it (if required) the sending caller ID must be maintained as an open comms channel during viewing. (Much like satellite download or Netflix recordings on demand.)
just use this
MyPDF

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.

Ajax/Javascript - File Download

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>

Downloading a music file instead of playing it in the browser

I'm trying to make a downloader on my website which starts downloading the selected files but the problem is it is a music file which just opens up in a new window and starts playing it.
The script is (don't worry about the id part it is for the next part):
function downloadsong(id){
var url = ("/music/downloadablesongs/linkin-park/Minutes-to-Midnight/wake.mp3");
window.open(url,'Download')
}
If you can configure the server that hosts the files, you should be able to manipulate the HTTP headers to include a "Content-Disposition" header. This will prompt the user agent (browser) to save the file, rather than allow it to automatically detect/interpret the content.
The basic format is:
Content-Disposition: attachment; filename=$file_name.ext
It depends on the user's browser. Usually, plugins or built-in browser capabilities take over and play it instead of letting the browser download.
What you can do is to have the file carry no extension (ie. remove .mp3). That way, it won't be picked-up by plugins. The down side is additional work for the user, by having to add the extension manually.
Other way is simply use the download attribute. I think is the simplest way.
<a href="/music/downloadablesongs/linkin-park/Minutes-to-Midnight/wake.mp3" download>
See more here.

Saving file from JavaScript string without hitting server

If I have an in-memory string in JavaScript that is let's say Excel or PDF format, and I want to pop open a save dialog so the user can save those bytes to a file, how would I go about doing this? I am trying to avoid going back to the server. If I was going back to the server I could send the correct HTTP headers in the response to tell the browser that I'm sending a file. But I want to do this from JavaScript instead because I already have the bytes I need on the client.
Is this possible?
Edit:
I should clarify what I'm actually looking for here. I am working with a Silverlight app. From Silverlight, I can pop up a save dialog and save the bytes (in this case, let's say they are Excel bytes). This seems to be what people are suggesting below when they suggest using Flash. Silverlight gives the same functionality.
But, I would prefer the the Excel file just opens in a new browser window. I could do that pretty easily if I was generating the file on the server, because I could just send the correct headers. But I already have the bytes in Silverlight on the client. Any way to open that doc in a new browser window so the user can just hit an Open button without having to pick a save location and navigate to the file?
And I can't use the out-of-browser application option. I know it would be possible using that by talking with Excel through COM-interop. But that's a no go in this case.
But I can interop with JavaScript from Silverlight. So I was hoping I could use JavaScript in some way to open a browser window and stream the Excel bytes to it.
You can use data URIs to embed the file in the HTML document; e.g., http://jsfiddle.net/dqWae/ creates a link that initiates a download of the Wikipedia title image. (The MIME type is hard coded as application/octet-stream but you can of course specify it as PDF or XLS).
You will need to encode the bytes of the file as base 64 and create a data URI for the resource. Then, create a new anchor element whose href attribute is the data URI. If you want to automatically initiate the download, programmatically issue a click event to the anchor element.
In JavaScript? I hope not, think of all the millions of security implications that would cause..
In pure javascript this will be possible only with html5 but not for now.
but you can do some javascript/flash 10 bridge, you pass the bytes to Flash who open the "save as" dialog and then you can save 100% client side.
The flash can be loaded dynamically.
see some code here : http://sujitreddyg.wordpress.com/2008/11/04/filereference-in-flash-player-10/
There are one non cross-browser solution (works only in Firefox, and only when user grant permissions).
// ask for security grants
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var pngBinary = 'some string';
var aFile = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
aFile.initWithPath( "/tmp/somefile.png" );
aFile.createUnique( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 600);
var stream = Components.classes["#mozilla.org/network/safe-file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(aFile, 0x04 | 0x08 | 0x20, 0600, 0);
stream.write(pngBinary, pngBinary.length);
if (stream instanceof Components.interfaces.nsISafeOutputStream) {
stream.finish();
} else {
stream.close();
}
But I recommend you to make cross-browser applications and choose Flash solution.

Categories

Resources