Javascript Blob Filename Without Link

JavaScript blob filename without link

The only way I'm aware of is the trick used by FileSaver.js:

  1. Create a hidden <a> tag.
  2. Set its href attribute to the blob's URL.
  3. Set its download attribute to the filename.
  4. Click on the <a> tag.

Here is a simplified example (jsfiddle):

var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());

var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";

saveData(data, fileName);

I wrote this example just to illustrate the idea, in production code use FileSaver.js instead.

Notes

  • Older browsers don't support the "download" attribute, since it's part of HTML5.
  • Some file formats are considered insecure by the browser and the download fails. Saving JSON files with txt extension works for me.

Download PDF from javascript blob, without replacing the open page

Eventually found a solution, incorrectly setting the MIME type on the blob breaks the browser's file type detection, and stops the built-in preview from starting.

const blob = new Blob([arrayBuffer], { type: "application/octet-stream" });

Can't set filename of Blob

Blob does not have a name attribute.

Preserve the original type, and use <a> element with download attribute with href set to to the Blob URL, call .click() on <a> element after appending the element to document.body.

blobGeneratingFunction.then(blob => {
let a = document.createElement("a")
let blobURL = URL.createObjectURL(blob)
a.download = 'test.png'
a.href = blobURL
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
})

Typescript blob filename without link

For chrome (and firefox) you need to do a little work around with creating an <a> element and calling click:

downloadFile(data: any): void {
const blob: Blob = new Blob([data], {type: 'text/csv'});
const fileName: string = 'my-test.csv';
const objectUrl: string = URL.createObjectURL(blob);
const a: HTMLAnchorElement = document.createElement('a') as HTMLAnchorElement;

a.href = objectUrl;
a.download = fileName;
document.body.appendChild(a);
a.click();

document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
}

URL.createObjectURL(blob): How do I give a "meaningful filename" to a dynamically generated .pdf?

One way is to save the file with a filename before it's opened. Unfortunately, this may not automatically open the file.

var fileLink = document.createElement('a');
fileLink.href = fileURL;
fileLink.download = title;
fileLink.click();

Another way is to generate the PDF and filename on your web server, and offer the link remotely, rather than generate the filename locally in the browser. This might offer you more consistent timestamps because they are generated by your server rather than all the clients in different timezones. Then you and your customers will be able to logically refer to identical documents if they have any questions.

JavaScript getting filename without extension located in different folder

This code will do what you're after.

  • First we find the position of the last / character appearing in the
    file-path.
  • Then we get the string that appears after the last / in the path.
  • Next we replace the '.js' part with nothing.

I've only performed a single check. That avoids printing an empty string for the script element that does all the work, since it's in the document and doen's have a source.

You'll need to add error-checking before this code is any good.

<head>
<script src="js/20231014.js" type="text/javascript"></script>
<script src="js/20211204.js" type="text/javascript"></script>
<script src="js/20230423.js" type="text/javascript"></script>
<script>
"use strict";
window.addEventListener('load', onLoad, false);

function onLoad(evt) {
let scripts = document.querySelectorAll('script');
scripts.forEach(scr => {
if (scr.src != '') {
let slashPos = scr.src.lastIndexOf('/');
let filename = scr.src.slice(slashPos + 1);
filename = filename.replace('.js', '');
console.log(filename);
}
});
}
</script>
</head>

Custom name for BLOB URL

Short answer, You can't.

This is an address that points to the browser's memory, where it has stored your blob, or a pointer to the original file in case of user uploaded file through the input type=file.

This is somehow by design. You can create multiple of these blobURLs from the same Blob. If they were to use a filename as URI, you couldn't.

Theoretically, it should be possible for you to dynamically create a page that would redirect to the BlobURI, and you could name this redirection page as you which. But this is just theory, I never tried to do it myself.

A rough proof of concept can be seen in this plunker, obviously, you'll need to generate blobRename.html dynamically, and change its name to the one you want, and also force it's content-header so that the browser thinks it's an html page if you want to get rid of the .html.
Also note that it doesn't seem to work with pdf files, which need browser plugins to trigger in, but with some more work, it may be possible to hack something around.

But anyway, I would just let the random url, your users will get more and more used to it as more and more web apps do use this great API.



Related Topics



Leave a reply



Submit