How to change URL.createObjectURL download name? - javascript

I'm building an online csv converter that allows a user to upload a csv file and download the processed csv output file. Everything works fine, except the dowloaded file has a name that looks like "6fd665aa-74d7-4b4e-96e1-38aea0cca9e6.csv" (it changes every time) that has nothing to do with the input file's name.
How can I change this downloaded file name ?
const processedStr = convertCSV(text);
const myBlob = new Blob([processedStr], {type : 'text/csv'});
dllink.href = window.URL.createObjectURL(myBlob);
dllink.click();

You can try to add an attribute to the dllink variable. It will give a name to the download attribute and hence the file.
const processedStr = convertCSV(text);
const myBlob = new Blob([processedStr], {type : 'text/csv'});
dllink.href = window.URL.createObjectURL(myBlob);
dllink.setAttribute("download","custom_name.csv"); // Added Line
dllink.click();

Related

Normalising the fileName in IE11 and creating of a new file in Javscript

I'm trying to upload a file, but i want to normalize it's name fisrt, it works on other browsers, but in IE11, i searched and i found out that this method (normalize) is not supported, so i'm using polyfill unorm. so normalizing works fine now, but we can't change the fileName directly, we need to create a new file. But we can't use new File because it's not supported too. So I used new Blob, but the problem is that i don't get the filename on the server side, it's always blob.
The code for other browsers :
var fileName = file.name.normalize('NFD').replace(/[\u0300-\u036f]/g, "");
var newFile = new File([file], fileName, { type: file.type });
newFile.label = 'FICHIER';
The code for IE11
fileName = unorm.nfd(file.name);
newFile = new Blob([file], { type: file.type });
newFile.label = 'Fichier';
newFile.name= fileName;
To generate the request to the server, i use formdata :
fd = new FormData();
fd.append("id", param);
fd.append(file.label || "uploadedFile", file, file[paramName]);
Can you tell me what should i do to get the filename or if there is another way to do this.
The Blob object doesn't contain the name property, so, we can't change name via the Blob object.
After getting the file data, I suggest you could append a new parameter to log the new file name, then, when submits the form or save the uploaded file, you could send the file data and the new file name to the server.
Besides, here is another thread about upload file using FormData, please refer to it:
Angular File Upload
File Upload using AngularJS

Angular - Save blob in local text file?

I have a plain text variable which I want to store and save on a .txt file using Angular.
So far I have tried the following:
var data = new Blob([text], {type: 'text/plain'});
const url= window.URL.createObjectURL(data);
window.open(url);
Being text the variable with the plain text content. It seems to work but it opens de blob on a new browser tab, and I need it to be downloaded as whatever.txt.
How can I achieve this? Thanks!
The solution can be found here:
JavaScript blob filename without link
The steps are the following:
Create a hidden <a> tag.
Set its href attribute to the blob's URL.
Set its download attribute to the filename.
Click on the <a> tag.
This is working code from my application
const file = new window.Blob([data], { type: contentType });
const downloadAncher = document.createElement("a");
downloadAncher.style.display = "none";
const fileURL = URL.createObjectURL(file);
downloadAncher.href = fileURL;
downloadAncher.download = fileName;
downloadAncher.click();

HTML5 input download (client only) seems to be limited by size

I want to download a file (client only) which contains a stringified JSON object. For months everything went well until I needed to stringify a big json object.
The text file is always created but the JSON object is simply cut off(if I change the json object it is cut off in different places).
I checked and the whole JSON object is correctly stringified and put into the href attribute but it is not totally present in the downloaded text file.
const file = document.createElement('a');
file.setAttribute('href', 'data:text/plain;charset=utf-8,' + JSON.stringify(jsonObj));
file.setAttribute('id', 'tcDownload');
file.setAttribute('download', fileName);
file.style.display = 'none';
document.body.appendChild(file);
file.click();
document.body.removeChild(file);
So I am wondering if where is some sort of size restriction while using client based downloading.
Works fine now thank you: epascarello
SOLUTION:
const str = JSON.stringify(tc);
var blob = new Blob(str.split(''), {type: 'text/plain'});
const file = document.createElement('a');
file.download = 'myFile.txt';
file.href = URL.createObjectURL(blob);
document.body.appendChild(file);
file.click();

New File stucks

I am new in javascript and was trying to read and write in local txt file so I did as I found in the web but for some reason it stucks in new File instantiation:
<script type="text/javascript">
var txtFile = "d:/test.txt"
alert('point 1');
var file = new File(txtFile);
alert('point 2');
</script>
It prints only 'point 1' string. Thanks.
new File() constructor requires at least two parameters; first parameter an array containing String, ArrayBufferView, ArrayBuffer Blob or another File object; the second the file name. You cannot specify a download directory for files using javascript, but you can set a download directory at browser settings or preferences. You can also utilize download attribute at a element to set file name at Save File dialog.
I am new in javascript and was trying to read and write in local txt
file
You could use <input type="file"> element to retrieve test.txt, and edit .txt file at <textarea> before re-saving with same file name. See also Edit, save, self-modifying HTML document; format generated HTML, JavaScript , How to Write in file (user directory) using JavaScript?
<script type="text/javascript">
var txtFile = "test.txt";
var text = "abc";
var file = new File([text], txtFile);
console.log(file);
var a = document.createElement("a");
a.download = file.name;
a.href = URL.createObjectURL(file);
document.body.appendChild(a);
a.innerHTML = file.name;
a.onclick = function() {
this.parentElement.removeChild(this)
}
</script>

Javascript Blob document with html tags to be saved with formatting

I am having some text like below to be saved in a downloadable doc format using javascript blob.
<p style='font-size:18px'>Hello</p>
Once the download happens I want the doc to show just show formatted 'Hello' without any html tags. In ubuntu this works very well.
But when I open the same doc in windows or google docs, I still see html tags.
Is there a way where I can do this formatting at Blob level itself. Below is the way Iam creating blob object.
var file = new Blob([val], {type: "octet/stream"});
Appreciate your help on this.
Try adjusting type of Blob to "text/html" , using URL.objectCreateURL() as file object reference for download
var val = "<div>abc</div>";
var file = new Blob([val], {
type: "text/html"
});
// file object reference
var download = URL.createObjectURL(file);
var a = document.createElement("a");
a.href = download;
a.download = "file-" + new Date().getTime();
document.body.appendChild(a);
a.click()

Categories