Download a file from URL with different file name - javascript

I have below functionality using JavaScript
The back end gives me a URL to download a file from like below -
https://something.org/FILENAME.ZIP
So I file name is fixed as FILENAME.ZIP
But while downloading a file , the file should get downloaded with custom file name like CUSTOMFILENAME.ZIP instead of FILENAME.ZIP
So,
1)The file should get downloaded from URL : https://something.org/FILENAME.ZIP
2)But it should get saved with different file name as :
CUSTOMFILENAME.ZIP
3)I have tried below programme from url - how to download a file from url using javascript or jquery?
var a = document.createElement("a");
a.href = url;
var fileName = CUSTOMFILENAME;
a.download = fileName;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
a.remove();
But still file gets downloaded with whatever file name mentioned in URL
Can anybody please help me here ?
The file should get saved with CUSTOMFILENAME I provide and not fileName specified as part of URL

Try this see if it works,
const documentName = "CustomFileName"; // here your file name
fetch("http://yourdomain.com")
.then(res => {
return res.blob();
})
.then(blob => {
const href = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.download = documentName;
a.href = href;
a.click();
a.href = "";
})
.catch(err => console.error(err));

you are giving a object as download name give a string

Related

JavaScript: Conditionally process fetch response

I have a fetch() request returning a Response object that is either a zip file (blob) or a JSON if there was an error with the request. The code I have successfully processes the zip file and sends it to the users Downloads folder. When a JSON response is returned, the code creates a empty/corrupt zip file.
How would I go about conditionally processing the Response object so that it prevents a file from being downloaded if it is a JSON? I would also like to store Response.json() in a variable?
await fetch(params)
.then(res => res.blob())
.then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = name + ".zip";
document.body.appendChild(a);
a.click();
a.remove(); //afterwards we remove the element
}).catch(err => console.error(err));
Thanks for the suggestions all. Per #Barmer and #Bergi suggestions I was able to redefine the API so that my error content is now just inside of a header. The solution I found looks like this:
await fetch(params)
.then(function(response) {
if (response.headers.get('X-Error') == 'False') {
return response.blob()
.then(blob => {
let url = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = url;
a.download = name + ".zip";
document.body.appendChild(a);
a.click();
a.remove();
}).catch(err => console.error(err))
}
//process error from backend
console.log(response.headers.get('X-Error'))
})

Download PDF in browser with blob

I can not quite wrap my head around on how to download a PDF from a google spreadsheet PDF Export Weblink. I generated a testing spreadsheet for this case.
I understand that I need to implement encodeURIComponent and/or "Buffer.from" to the blob but however I do it, it only downloads a broken PDF for me.
This is what I currently have in its rawest form. Thank you for your support!
Node JS:
const fetch = require('node-fetch');
var url = "https://docs.google.com/spreadsheets/d/1fLjKASR_g5wsvOjjJi6RclqMVd2o_1On-OfimXtId4E/export?exportFormat=pdf&format=pdf&size=A4&fzr=true&gid=477517973&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&portrait=true&fitw=true&fith=true&top_margin=0.20&bottom_margin=0.20&left_margin=0.20&right_margin=0.20";
let blob = await fetch(url).then(r => r.blob());
// then send blob variable to javascript
Javascript:
function downloadURI(name) {
var uri = 'data:application/pdf;base64,' + blob;
var link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
downloadURI("test"+".pdf")
I thought that from var uri = 'data:application/pdf;base64,' + blob; in your script, in this case, it is required to convert the downloaded data as the base64. Although I'm not sure about the relationship between the scripts between Node JS: and Javascript:, in your situation, how about the following modification?
From:
let blob = await fetch(url).then(r => r.blob());
To:
let buf = await fetch(url).then((r) => r.arrayBuffer());
const data = Buffer.from(buf).toString("base64");
By this, you can use data as follows.
var uri = 'data:application/pdf;base64,' + data;
Note:
As the additional information, for example, if you want to download your Spreadsheet as a PDF file using only Javascript, you can also use the following script. But, in this case, the Spreadsheet is required to be publicly shared. Please be careful about this.
async function downloadURI(name) {
var url = "https://docs.google.com/spreadsheets/d/1fLjKASR_g5wsvOjjJi6RclqMVd2o_1On-OfimXtId4E/export?exportFormat=pdf&format=pdf&size=A4&fzr=true&gid=477517973&sheetnames=false&printtitle=false&pagenumbers=false&gridlines=false&portrait=true&fitw=true&fith=true&top_margin=0.20&bottom_margin=0.20&left_margin=0.20&right_margin=0.20";
let blob = await fetch(url).then((r) => r.blob());
var f = new FileReader();
f.readAsDataURL(blob);
f.onload = d => {
var uri = d.target.result;
var link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
}
downloadURI("test"+".pdf")

JS download doesn't download entire file

I am trying to download a csv file with 3607 lines (1.0 Mb):
const hiddenElement = document.createElement('a');
const fileContent = `data:text/csv;charset=ansi,${res.data}`;
hiddenElement.href = fileContent;
hiddenElement.target = '_blank';
hiddenElement.download = 'file.csv';
hiddenElement.click();
The content at res.data is complete (as well as fileContent), but when i download the csv, the file only has 149 lines (4.4 Kb) instead of the original size.
Can someone help me please?
The problem was that URLs cant have more than 2,048 characters
I faced the same problem and the same CSV download used to work earlier and download complete file.
had to change to the following:
const blob = new Blob([csvData], { type: 'text/csv' })
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a')
link.setAttribute('href', url)

change file name in angular when download that by "Blob"

i want to download file from server in angular :
this code from service:
DownloadVerifyFile(requestId, fileId): any {
return this.httpClient
.get(this.appConfig.apiEndpoint + '/VerifyRequest/File/' + requestId + '/' + fileId,
{ responseType: 'blob' });
}
and this code for download that file in brwoser:
DownloadFile(fileId): void {
this.requestService.DownloadVerifyFile(this.id,fileId).subscribe(response => {
const a = document.createElement('a')
const objectUrl = URL.createObjectURL(response)
a.href = objectUrl
a.download = response;
a.click();
URL.revokeObjectURL(objectUrl);
});
}
but i have a problem with that , when i downlaod file , file name is this [object Blob] but i want to download by orginal name for example if file is file1.jpg , when downloaded file name must be fil1.jpg not [object Blob] . how can i solve this problem ???
Because you have named the file by response(It is an object). You were almost achieved. Just a little change as following:
a.download = response;
to
a.download = 'fil1.jpg';
Then you will get the correct file name.

Is it possible to convert byte array/stream to files such as Word,Excel, PDF in JavaScript

I have a query regarding file operations using JavaScript-
Scenario - My JS function calls a wcf service which returns the file content in the form of byte array or stream and the mime type. This byte array/stream needs to be converted to a file and which will be downloaded on user's machine.
Reference code -
var arr = "This is test content";
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], {
type: 'text/plain'
}));
a.download = "Test";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
The code works for only text files. Files with mime type other than text are corrupted.
I understand that file operations are severly restricted at client side, but just to confirm - Is there anyway to convert byte array/stream to files such as Word,Excel, PDF and etc ?
I accomplish a similar goal with this. Pick up from where you have your byteArray, and try this:
var byteArray = new Uint8Array(arrayBuffer);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type:'application/octet-stream' }));
// supply your own fileName here...
a.download = "YourFileName.XLSX";
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
Setting contentType to "application/octet-stream" will accommodate any binary file type.

Categories