I have a page on my website which has a button, that redirects to a URL, that downloads the source code of the git repo for that website. Here is the HTML I have so far:
<!DOCTYPE html>
<html>
<body>
<p>Would you like to download this website's source code?</p>
<button type="button" onclick="window.location.href = 'https://codeload.github.com/SteepAtticStairs/steepatticstairs.github.io/zip/refs/heads/main'">Yes</button>
<button type="button" onclick="window.location.href = '/index.html'">No</button>
</body>
</html>
However, this downloads a file with the name steepatticstairs.github.io-main.zip. I have a bash script that I wrote:
#!/bin/bash
url=https://codeload.github.com/SteepAtticStairs/steepatticstairs.github.io/zip/refs/heads/main
now="$(date '+%m.%d.%Y')"
cd ~/Downloads
wget -O "steepatticstairs.github.io_${now}.zip" $url
Which downloads the file with a name like steepatticstairs.github.io_03.09.2022.zip. This is the name that I want - with the date at the end.
Is there any way that I could replicate this in JavaScript, perhaps using jQuery, where I could click the Yes button and it would download the file from the URL, but it would rename it before download? If someone is able to quickly show me how to also get the date into the filename in JavaScript, that would be awesome, but I would be able to figure that out. I just want to know how to rename the file before downloading.
because cross-domain the ajax will blocked by CORS policy,you need the server to proxy the request and modify the Content-Disposition in the response header, for example: Content-Disposition:attachment;filename= ${filename}.zip
you can use ajax to download file:
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.addEventListener('load', () => {
if (xhr.status === 200) {
const a = document.createElement('a');
const url = window.URL.createObjectURL(xhr.response);
a.href = url;
a.download = '${filename}.zip';
a.click()
window.URL.revokeObjectURL(url);
}
});
// if need progress bar can listen progress event
// xhr.addEventListener('progress', e => console.log(e.loaded/e.total))
xhr.open('GET', '${url}')
xhr.send()
Related
In my application written in Ionic 5 and Angular 8, I am in need to download multiple PDF links (file) in the same page on click of the link. I tried but the PDF links are opening in browser. Request to help me achieve this functionality.
https://stackblitz.com/edit/ionic-yzzwov?file=pages%2Fhome%2Fhome.html
The download attribute appears normal when same-origin, otherwise it will appear the same as without download attribute.
list three solutions:
Package the file into a file type that cannot be opened directly by the browser, such as ZIP
Through forwarding by the back end, the back end requests a third-party resource and returns it to the front end, which saves the file using tools such as file-Saver
If the third-party resource the URL points to has CORS configured, you can request the file through XHR
downloadFileXHR(filePath, fileName) {
var xhh = new XMLHttpRequest()
xhh.open('get', filePath)
xhh.responseType = 'blob'
xhh.onreadystatechange = function () {
if (xhh.readyState === 4 && xhh.status === 200) {
var blob = new Blob([xhh.response])
var csvUrl = URL.createObjectURL(blob)
var link = document.createElement('a')
link.href = csvUrl
link.download = fileName
link.click()
}
}
xhh.send()
User click on the button on the webpage to download the file, i want to track the file is being downloaded to the user machine or not using client side code like javascript/JQuery.
On button click, ASP.NET .ASHX Web handler code is called which return the file to be downloaded.
Also can we check using javascript/JQuery whether the user is having issue (security, firewall etc.) in downloading the file, when user click on the download button on the webpage.
This can be done via the "progress" event that is attached to an AJAX request.
let xhr = new XMLHttpRequest();
xhr.addEventListener("progress",event=>{
console.log(`${event.loaded} out of ${event.total}`);
});
The download can then be handled via AJAX by creating a false link that links to the file data which will be saved in memory:
xhr.onreadystatechange(function(){
if(this.readyState==4 && this.status==200){
//Download content via imaginary link with data saved in memory
var a = document.createElement('a');
var url = window.URL.createObjectURL(this.response);
a.href = url;
a.download = 'myfile.pdf';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}else if(this.status==404){
console.error("page not found");
}
});
xhr.open("GET","myfile.pdf",true);
xhr.responseType = "blob";
xhr.send();
I am trying to download a file using jQuery. The problem is I have no reference about the file extension. I only know the file name. The file name is unique because it shares the same name with the primary key. So, no file is the same.
This is the jQuery I use:
$("#tbl_surat_all tbody").on('click','.row_surat', function(e) {
var no_s = $(this).find('a').html(); //get the file name
var b_url = $('#base_url').val()+"assets/uploads/surat/"; //base_url
var url = b_url+no_s; //download_url
window.location = url; //script_to_download
});
How do I download the file by only knowing the file name??
Note:
I have no privilage to change table structure, so I can't update the upload script.
The file are images, pdfs, and rars
There is no way to open the file from the server without sending a valid request.
If you don't request the complete file name with extension, you will get an error.
So the only workaround would be to request all possible file extensions.
We could try to include the following:
.jpeg .jpg .png .pdf .rar
And then iterate it with requests.
Since this would open a **** load of windows, we will be immediately closing them, so it will look relatively smooth.
Here is the code:
var url_base='http://127.0.0.1/base_url/file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];
for (i=0;i<ext_arr.length;i++){
var url=url_base+ext_arr[i];
window.open(url)
.addEventListener('load', function(){
this.close();
}, false);
}
Note: do note that in order for it work properly, requested files must meet the same origin policy.
Edit: I have modified the above code to load resources in background via xhttp requests and then output it directly for download.
This method should work flawlessly for all types of files, and it's also the fastest!
var url_base='http://127.0.0.1/';
var file_name='file_without_extension';
var ext_arr=['.jpeg', '.jpg', '.png', '.pdf', '.rar'];
for (i=0;i<ext_arr.length;i++){
// Define request url
var url=url_base+file_name+ext_arr[i];
// Use XMLHttpRequest instead of Jquery $ajax
var xhttp = new XMLHttpRequest();
// Set the url as a property
xhttp['user_filename']=file_name;
// Bind on ready function
xhttp.onreadystatechange = function() {
var a;
// Check if page has loaded successfully
if (this.readyState === 4 && this.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(this.response);
// Filename for downloading
a.download = this.user_filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
a.parentNode.removeChild(a);
}
};
// Set request url and method
xhttp.open("GET", url);
// Set responseType as blob for binary response
xhttp.responseType = 'blob';
// Send request
xhttp.send();
}
I am uploading a file to Amazon S3 Bucket using pre-signed URL from AngularJs. Zip file getting corrupted while opening the downloaded file. It is working as expected when I upload the file from postman in binary format.
I am using ng-file-upload library in angularjs. For every downloaded file contains web-kit form boundary appended in the beginning as follows:
If we edit and remove the web-kit form boundary and try to open the same file its opening perfectly.
I experienced the same problem the week ago and the only solution I came up with, was to write my own code which sends files via http request. Feel free to use the example:
function azureChangeFn() {
var inputElement = document.getElementById("fileSelect");
var newFile = inputElement.files[0];
var url = "https://YOUR_STORAGE_NAME.blob.core.windows.net/CONTAINER_NAME/"+ newFile.name +"GENERATED_SharedAccessSignature_FROM_AZURE_SITE";
var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress);
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert("Sent to azure storage service!");
}
}
xhr.open('PUT', url, true);
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.setRequestHeader("lng", "en");
xhr.setRequestHeader("x-ms-blob-type", "BlockBlob");
xhr.setRequestHeader("x-ms-blob-content-type", newFile.type);
xhr.send(newFile);
}
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
console.log(percentComplete);
} else {
alert('FAIL');
}
}
<html>
<head>
</head>
<body>
<label>Example without library:</label>
<br>
<label>Select file: <input type="file" id="fileSelect" onchange="azureChangeFn()"></label>
</body>
</html>
Talking about ng-file-upload library, in source code I found that formData.append method when appending a file, automaticaly adds web-kit header. As far as I understood, FormData is used for POST method, but when using PUT all body is taken as a file. Sadly I was unable to upload file to azure storage with POST method.
Images are hosted outside the server and are downloaded only to the user (client side).
I have tried the HTML5 download tag, but it does not work very well with IE.
<div style="width:800px; height:457px; background-image:url('http://i.imgur.com/7fypLpI.jpg');"></div>
Download
https://jsfiddle.net/eLpc8d7u/
How can I download the files for example with JavaScript for any browser?
I've seen this other question: IE download file
But I'm still confused to make a single script.
For cross browser download including IE < 10 and IE >= 10, you can use the below library which will do task easy for you.
http://danml.com/js/download.js
GitHub Location: https://github.com/rndme/download
Sample code snippet for your case:
function downloadImage(event, url, fileName) {
event.preventDefault();
if(window.download && url) {
fileName = fileName || url.split('/').pop().split('?')[0];
var ajax = new XMLHttpRequest();
ajax.open( 'GET', url, true);
ajax.responseType = 'blob';
ajax.onload= function(e){
download(e.target.response, fileName, 'application/octet-stream');
};
setTimeout(function(){ ajax.send();}, 0); // allows setting custom ajax headers using the return:
return ajax;
}
}
<script src="http://danml.com/js/download.js"></script>
<div style="width:800px; height:457px; background-image:url('http://i.imgur.com/7fypLpI.jpg');"></div>
Download with default file name<br/>
Download with custom file name