Code Monkey home page Code Monkey logo

download's Introduction

download

NPM version Size License CDNJS

Summary


The download() function is used to trigger a file download from JavaScript.

It specifies the contents and name of a new file placed in the browser's download directory. The input can be a URL, String, Blob, or Typed Array of data, or via a dataURL representing the file's data as base64 or url-encoded string. No matter the input format, download() saves a file using the specified file name and mime information in the same manner as a server using a Content-Disposition HTTP header.

Getting and Using


Via NPM/Bower

npm install downloadjs
bower install downloadjs

require("downloadjs")(data, strFileName, strMimeType);

Simple global download function via <script> include

download(data, strFileName, strMimeType);

Included via AMD

require(['path/to/file'], function(download) {
    download(data, strFileName, strMimeType);
});

Parameters


  • data - The Blob, File, String, or dataURL containing the soon-to-be File's contents.
  • strFileName - The name of the file to be created. Note that older browsers (like FF3.5, Ch5) don't honor the file name you provide, instead they automatically name the downloaded file.
  • strMimeType - The MIME content-type of the file to download. While optional, it helps the browser present friendlier information about the download to the user, encouraging them to accept the download.

Example Usage


Plain Text

text string - live demo

download("hello world", "dlText.txt", "text/plain");

text dataURL - live demo

download("data:text/plain,hello%20world", "dlDataUrlText.txt", "text/plain");

text blob - live demo

download(new Blob(["hello world"]), "dlTextBlob.txt", "text/plain");

text url - live demo

download("/robots.txt");

text UInt8 Array - live demo

var str= "hello world",	arr= new Uint8Array(str.length);
str.split("").forEach(function(a,b){
  arr[b]=a.charCodeAt();
});

download( arr, "textUInt8Array.txt", "text/plain" );

HTML

html string - live demo

download(document.documentElement.outerHTML, "dlHTML.html", "text/html");

html Blob - live demo

download(new Blob(["hello world".bold()]), "dlHtmlBlob.html", "text/html");

ajax callback - live demo

(note that callback mode won't work on vanilla ajax or with binary files)

$.ajax({
		url: "/download.html",
		success: download.bind(true, "text/html", "dlAjaxCallback.html")
});

Binary Files

image from URL - live demo

download("/diff6.png");

Image via ajax for custom filename - live demo

var x=new XMLHttpRequest();
x.open( "GET", "/diff6.png" , true);
x.responseType="blob";
x.onload= function(e){download(e.target.response, "awesomesauce.png", "image/png");};
x.send();

Compatibility


download.js works with a wide range of devices and browsers.

You can expect it to work for the vast majority of your users, with some common-sense limits:

  • Devices without file systems like iPhone, iPad, Wii, et al. have nowhere to save the file to, sorry.
  • Android support starts at 4.2 for the built-in browser, though chrome 36+ and firefox 20+ on android 2.3+ work well.
  • Devices without Blob support won't be able to download Blobs or TypedArrays
  • Legacy devices (no a[download]) support can only download a few hundred kilobytes of data, and can't give the file a custom name.
  • Devices without window.URL support can only download a couple megabytes of data
  • IE versions of 9 and before are NOT supported because the don't support a[download] or dataURL frame locations.

FAQ


  • Can I tell when a download is done/canceled? No.
  • How can I style the temporary download link? Define CSS class styles for .download-js-link.
  • What's up with Safari? I don't know either but pull requests that improve the situation are welcome.
  • Why is my binary file corrupted? Likely: an incorrect MIME or using jQuery ajax, which has no bin support.
  • How big of files work? Depends, try yourself: File Echo Demo... I do a 1GB dl routinely on a thinkpad...

Change Log (v4.1)


  • 2008 :: landed a FF+Chrome compatible way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
  • 2012 :: added named files via a[download], msSaveBlob() for IE (10+) support, and window.URL support for larger+faster saves than dataURLs
  • 2014 :: added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support
  • 2015 :: converted to amd/commonJS module with browser-friendly fallback
  • 2015 :: 4.1 added direct URL downloading via a single URL argument.
  • 2016 :: 4.2 added large dataURL support, a more semantic codebase, and hidden temp links
  • 2017 :: added support for empty dataURLs
  • 20XX :: ???? Considering Zip, Tar, and other multi-file outputs, Blob.prototype.download option, and more, stay tuned folks.

download's People

Contributors

ciaranj avatar extend1994 avatar glittle avatar jantimon avatar jpstevens avatar msokk avatar rndme avatar sliekens avatar x-raym avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

download's Issues

Compatibility with IE11?

Arggh, ignore this Issue, I was being a massive tool and had not uploaded the right files to our dev server when testing on IE. Seems to work fine on IE11. I'll delete this Issue if I find out how...

Not all content types described by RFC 2045 are supported when using data urls

As described by RFC 2045, all US-ASCII characters except SPACE, CTLs or tspecials are allowed in the content type.

The regular expression detecting data url usage only checks for words (\w) and dashes (\-).

How to reproduce:
Use a data url with a content type containing a dot (.) character.

For example:
data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,<BASE64_ENCODED_DATA>

error: download is not a function

I don't know how to describe it properly, and neither do I have a MRE.
But it seems that if the main function is called "download", that creates an error as described in the title.

I have renamed your function to something else (e.g. "downloadit") and then it worked.

No idea what might be triggering this error (I am using OS X version 10.9.5 and Chrome Version 64.0.3282.167), but I hope this might be of help somehow.

Expose the limitations programatically

This is a great lib for downloading, event though it is supported in modern browsers some people are in older browser for them i want to show which file is download or not download, to do so expose the limitations via isChromeSupoort,isIESupport like that variables.

1.4.6+ broke downloading files with non-ASCII charachers

We are using download.js to download CSV/TSV/etc. data from query application, see source code here: https://github.com/wikimedia/wikidata-query-gui/blob/master/wikibase/queryService/ui/App.js#L515

With 1.4.4, it worked just fine. With 1.4.6+, however, the data is downloaded broken - non-ASCII characters are mangled. Looks like some changes in 1.4.6 broke something in non-ASCII download.

The resulting files for comparison:
1.4.4: https://gist.github.com/smalyshev/e4c02c94f1433111f7100836496d7eff
1.4.6+: https://gist.github.com/smalyshev/379b46d1a0b8bec7953f26a7c4261800

I've tested in Chrome, but other browsers are reported by users to produce similar results.

NPM Package

Would love an NPM package for those of us that use it!

How is the message to download file appear

I have been working with this library for last week now. In the beginning the file download message was coming at the bottom of the browser like this
image5

I have seen it change to opening a save as window
image4

and Today it just opens the file in jpeg, doesn't give a window message or show the file download bottom of the file, just simply opens it in photos,

Do we know what drives that behavior?

Thanks

Asynchronous?

Hi, thanks for this awesome library. I just have a couple questions.

1.) is the download function asynchronous?
2.) is there a way notify the calling code when it is done?

My motivation for asking is that I want to close the parent window when the download starts or completes.
I know this isn't really an issue with the code, just wondering if I can make it do what I want:)

Chrome breaks if base64 url is bigger than 2MB

This is quite an old bug but it looks like it has not been resolved yet. Basically when I try to use your plugin to download a base64 that is bigger than several MB (from a canvas), I get "network error" instead of the proper file.
Probably you should switch to Blob if the base64 string is too long.

PDF download

Hi,

I have few PDFs available on a URL, and I want to allow user to download them. I tried passing PDF as URL, but it did't work.

In example available on http://pagedemos.com/yvvmxbjrwq7u/2 , I replaced code for image download from:
download( "/diff6.png" );
to
download( "www.example.com/diff6.pdf" );

but it did't work. Do we need to do any changes for PDF to get downloaded successfully?

Thanks.

Support download of MS Office docx and xlsx files

Thank you for this great resource. I'm using it to download files returned from a request that uses a proxy and the link to the documents cannot simply be placed in an <a href>

I can successfully download all file types with the exception of the microsoft office docx and xlsx types. When attempting to open the downloaded files with MS Office I get an error message stating that they are corrupt and cannot be repaired.

I have tried including the correct mime type
application/vnd.openxmlformats-officedocument.wordprocessingml.document

AND

leaving the mime type blank (and defaulting to application/octet-stream)

Both result in corrupted file.

Any ideas how to support the download of those file types correctly?

my code:

var x = new XMLHttpRequest();
 x.open("GET", attachUrl, true);
 x.responseType = 'blob';
// with correct mime type
//x.onload = function (e) { download(x.response, name, file.ContentType); }
// without mime type
x.onload = function (e) { download(x.response, name); }
console.log(file.ContentType);
x.send();

and the error message in MS Office
corrupt

Set Folder to download

How can I set a specific folder to download the file, instead of the default folder "Downloads"?

Error with Uint8Array input

I got an Exception about saying payload.charCodeAt is not a function at line 78 when I was testing this library with an Uint8Array input.

When downloading from URL, allow custom filename

To download from a URL, currently I have to provide a single argument, which is the URL itself. The filename will be automatically determined from the URL. If I added the second filename argument, downloadjs will treat it like downloading blob url.

I think it should be possible to still treat it like downloading from URL, and use the second argument as filename instead of determining from the URL. Something like:

download('https://example.com/1234-5678-9012.pdf', 'mine.pdf')

Cannot open PDF file after download

Please help to check, this is my code:

  var fileUrl = form.vals().download;
  var fileName = fileUrl ? fileUrl.replace(/^.*[\\\/]/, '') : '';
  download(fileUrl, fileName, "application/pdf");

After download, that file can not open:
image

Safari 7.1 download

I've tried setting up a simple string download which works fine in Chrome and Firefox but not in Safari 7.1. After triggering the download I can see the data being inserted into the current page real quick and then it disappears.

download('This is some string', filename, 'text/plain');

Safari Issue

I saw that for safari the image is opened in the tab and the user should save it manually which is acceptable. My problem is that when i have multiple images and i call download function many times one after the other , the confirm popup appears as many times as images i have and i have to press ok for every each of them, but the main problem is that I can see only the last image, all the others are lost.

Silent Mode

Is it possible to hide the message of download (silent mode)!

download file from URL

Hi,

maybe it's a simple question, but I can't make it myself:

how has the function to look alike if I want to download an existing file?

like the filename is "image.jpg"?

thank you!

Issue with mp4 download and filename parameter

When I download an mp4 with only a single parameter all is good:
download(highestQuality);
If I add a filename parameter it downloads a text file with the URL as the contents:

downloadName = videoName + '.mp4';
download(highestQuality,downloadName);

I tried using a static string for the name and added the mimetype, but neither helped.

Am I misunderstanding something, or is this a limitation?
Thanks-
Matt

An error in IE10-11: InvalidStateError

Here is a fix, taken from bpampuch/pdfmake#294:

line 82:
try {
blob = payload instanceof myBlob ?
payload :
new myBlob([payload], {type: mimeType}) ;
}
catch (e) {
// Old browser, need to use blob builder
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
if (window.BlobBuilder) {
var bb = new BlobBuilder();
bb.append(payload);
blob = bb.getBlob(mimeType);
}
}

docx, ods

Hi,
in my app i was using just this piece of js:

var link = document.createElement("a"); link.download = dataItem.Filename; link.href = data; link.click();

where data is the data uri with mime type etc...
this is working perfectly on chrome, but not in ie
so i used your library, and it's perfect for ie
the only issue is that is not working with documents like docx, ods...

add download progress

Hi do you think you could add some download progerss in % in console.log as file downloads?

Thanks for Anwsering and Best Regards

Bower

Hello,
Your lib is very cool, you should publish it into the bower repository, so we will include easily in our project.

good job ๐Ÿบ

Cross-Origin Issue

For all other request cross origin issue doesn't come as cors is already implemented in node side but when i use download(url). It throws cors error?
fas

Issue in downloading excel sheet.

I am using REST API @ back and it provides the byteStream of the excel file and I am trying to generate file @ client Side.
File is downloaded but the content stores as the same the server responds to the front end.

Server problem when loading src within script tag.

Hi there,

Thank you for the nice work, I have been using your download script over 2 years. I recently bumped into an issue in chrome with download.js. When loading from script tag:

<script src="http://danml.com/js/download.js"></script>

chrome seems to wait forever, as a result, page dependent on it will never load unless they are loaded async. Firefox seems to have a cached version in my pc. I cannot seem to connect to your website from chrome either. Are you changing files on the server or is this new behavior intended?

Thank you for your work once again,

Problem with Chrome on iOS

I tried every single demo but neither works on Chrome on iPhone, working on solution for iPhone/iPad download and considering your lib as a potential fix.

Data URI decoder is not selected properly

		function dataUrlToBlob(strUrl) {
			var parts= strUrl.split(/[:;,]/),
			type= parts[1],
			decoder= parts[2] == "base64" ? atob : decodeURIComponent,
			...
		}

https://github.com/rndme/download/blob/master/download.js#L90

This one fails, it is generated with google first hit from text:

data:text/plain;charset=utf-8;base64,w4FydsOtenTFsXLFkXTDvGvDtnJmw7p0w7Nnw6lwLg==

The problem that the charset is given, so the second part is the charset rather than the encoding. You should parse the heading part of the URI instead of making presumptions on its structure.

Does not seem to work with "audio/mpeg" mime format

Got an audio file coming in through ajax and when ajax receives it the file is the right size with correct headers but once its run through download it almost doubles in size and is not readable by mp3 players.

Download image/jpeg image from a Buffer object

I'm trying to download a image file from a JSON object:

{"type":"Buffer","data":[255,216,255,224,0,16,74,70,7...]}

download(new Blob(buffer.data, {type: "image/jpeg"}), "image.jpeg", "image/jpeg");

but the downloaded file is not valid image. Do i have to perform previous convertion with the Buffer object? any help?

EDIT: my bad.
The `"data":[255,216,255,224,0,16,74,70,7...]}`` from the JSON object is not a actually Buffer, just a String representation of it. Changed my API to return a Base64 String of the file.

support Chinese link download

change code

if(url && url.length< 2048){ // if no filename and no mime, assume a url was passed as the only argument
			fileName = url.split("/").pop().split("?")[0];
			anchor.href = url; // assign href prop to temp anchor
		  	if(anchor.href.indexOf(url) !== -1){ // if the browser determines that it's a potentially valid url path:
        		var ajax=new XMLHttpRequest();
        		ajax.open( "GET", url, true);
        		ajax.responseType = 'blob';
        		ajax.onload= function(e){ 
				  download(e.target.response, fileName, defaultMime);
				};
        		setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
			    return ajax;
			} // end if valid url?
		} // end if url?
fileName = url.split("/").pop().split("?")[0];
url = encodeURI(decodeURI(url));
anchor.href = url

can support Chinese filename

Customize behaviour when identifies that the browser is Safari.

Hello everyone!

I want to customize the behaviour when the browser is Safari. Everybody knows that the Safari isn't support the a[download] attribute yet and, i want to handle the behaviour more customizable. For that, I implemented a simple solution for, just passing an option parameter to the download function but i'm in doubt about the flexibility and customizability for that solution.

I'll send a PR but discussion is opened!
Best regards.

Great library thanks!

Safari still refuses to download... tries to open up the file in a new tab or window. Any way to workaround this? I need to be able to save a client side code generated file in blob or objectURL format to a user's downloads folder.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.