Save file Javascript with file name
Replace your "Save" button with an anchor link and set the new download
attribute dynamically. Works in Chrome and Firefox:
var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");
Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/
Here a compatibility table for download
attribute: http://caniuse.com/download
How to download file with filename?
Assuming you have a blob called abc.png
and you want it to be downloaded as def.png
, what you could do is overwrite Content-Disposition
header in your SAS token. Then when the user clicks on the download link, the file will be saved as def.png
by default.
Please see the sample code below:
private static void OverrideContentDispositionHeaderInSharedAccessSignature()
{
var cred = new StorageCredentials(accountName, accountKey);
var account = new CloudStorageAccount(cred, true);
var blobClient = account.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("container-name");
var blob = container.GetBlockBlobReference("abc.png");
var sasConstraints = new SharedAccessBlobPolicy();
sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5);
sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10);
sasConstraints.Permissions = SharedAccessBlobPermissions.Read;
var sasBlobHeaders = new SharedAccessBlobHeaders()
{
ContentDisposition = "attachment; filename=\"def.png\""
};
var sasBlobToken = blob.GetSharedAccessSignature(sasConstraints, sasBlobHeaders);
var sasUrl = blob.Uri.AbsoluteUri + sasBlobToken;
}
With this you don't need to set the download
attribute on your link element. Your client side code would be much simple. Something like:
let a = document.createElement('a');
a.href = data.url
a.click()
document.removeChild(a)
Using HTML5/JavaScript to generate and save a file
OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:
1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).
2) Build the data URI:
uriContent = "data:application/octet-stream," + encodeURIComponent(content);
There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.
3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:
newWindow = window.open(uriContent, 'neuesDokument');
That's it.
How to rename or keep the file name only while downloading the file entering a required key?
There are multiple ways to solve your problem. The most simple solution is to set the download
attribute without value
link.download = '';
This will use the final segment of the URL as filename.
download
Causes the browser to treat the linked URL as a download. Can be used with or without a value:
Without a value, the browser will suggest a filename/extension, generated from various sources:
- The Content-Disposition HTTP header
- The final segment in the URL path
- The media type (from the Content-Type header, the start of a data: URL, or Blob.type for a blob: URL)
Defining a value suggests it as the filename. / and \ characters are converted to underscores (_). Filesystems may forbid
other characters in filenames, so browsers will adjust the suggested
name if necessary.
MDN
Javascript: set filename to be downloaded
i wrote a tool you can use to save a file to the downloads folder of the local machine with a custom filename, if that's possible on the client's machine.
as of this writing, you need chrome, firefox, or IE10 for that specific capability, but this tool falls-back to an un-named download if that's all that's available, since something is better than nothing...
for your use:
download(csv, "dowload.csv", "text/csv");
and the magic code:
function download(strData, strFileName, strMimeType) {
var D = document,
a = D.createElement("a");
strMimeType= strMimeType || "application/octet-stream";
if (navigator.msSaveBlob) { // IE10
return navigator.msSaveBlob(new Blob([strData], {type: strMimeType}), strFileName);
} /* end if(navigator.msSaveBlob) */
if ('download' in a) { //html5 A[download]
a.href = "data:" + strMimeType + "," + encodeURIComponent(strData);
a.setAttribute("download", strFileName);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
a.click();
D.body.removeChild(a);
}, 66);
return true;
} /* end if('download' in a) */
//do iframe dataURL download (old ch+FF):
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + strMimeType + "," + encodeURIComponent(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
} /* end download() */
update: added future-resistant IE routine
update2: checkout the evolved version on GitHub that includes dataURL and Blob support.
Related Topics
JavaScript on the Bottom of the Page
How to Use Google.Maps.Event.Trigger(Map, 'Resize')
Creating Drop Down Menu on Click CSS
Increment a Number in a String in with Regex
Decode HTML Entities in JavaScript
Change the Style of an Entire CSS Class Using JavaScript
Counting and Limiting Words in a Textarea
Writing File to Desktop Using HTML5 Filesystem API
Appending Form Input Value to Action Url as Path
Detect Browser Wrapped Lines via JavaScript
Open a New Tab with JavaScript But Stay on Current Tab
How to Put Codes from Jsfiddle.Net into My Website
What Tag in HTML Should I Use Without Special Meaning, Only to Carry Meta Data
How to Change the Font (Family) for the Labels in Chart.Js
Changing the Order of Elements