Force file download once a site is visited - html

I have a simple site example.com and an external file link. I want this scenario to be implemented:
Once a user visits example.com, a file from an external link is automatically downloaded.
Mind that I don't want a user to click some link, but just an immediate file download once the site is visited. Thus <a href="link/to/file" download>Download</a> is not what I need.
Thanks in advance.

Simply create a link and click on it via js:
<script>
window.onload = function(){
var a = document.createElement("a");
a.href = "link/to/file";
a.download = true;
a.click();
};
</script>

Related

How to download a file uploaded on google cloud storage instead of viewing it?

I upload a file on google cloud storage and sends the url to an ejs file in which i assign its url to a button. When i click on the button, I want to download the file instead of viewing it in browser. How can i make it possible?
Ejs file code
<div class="send-btn-container">
<a
href="<%= downloadLink %>"
download
target="_blank"
type="application/octet-stream"
>Download file</a>
</div>
As of late 2018, clicking the link won’t trigger a download if the resource to be downloaded wasn’t served from the same origin or same server so to say. Apparently, this restriction is a security measure.
I am using my react code as example to show you a way to download a file from GCloud storage.
const download = (e) => {
e.preventDefault();
// Remote URL for the file to be downloaded
const url = 'https://storage.googleapis.com/...';
const filename = "mypdf.pdf";
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const blobURL = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = blobURL;
a.style.display = 'none';
if (filename && filename.length) a.download = filename;
document.body.appendChild(a);
a.click();
})
.catch((error) => {
console.error(error);
});
};
<a onClick={(e) => download(e)}>
Download file
</a>
convert into a blob URL instead.
I am answering this in regard to HTML5. If you want the file to be downloaded instead of viewing it, you can add download attribute to <a> tag as follows:
<a href="downloadLink.pdf"
download="mypdf.pdf" <!-- This will force download the file -->
target="_blank"
type="application/octet-stream" </a>
In this case, the file downloadLink.pdf will be downloaded as mypdf.pdf but this attribute is currently supported in chromium browsers only.

refresh data read from text file with out page refresh

i am a novice at Java and JS so this will be very basic.
I've got this code that creates a text file in a specific directory. i only got as far as creating an actuale file, however, as the text file will be frequantely updated, i need the page to refresh/reload the text file and display it's data (just in the blank page). How do i do this, with out user needed to click refresh (auto refresh in sense, however, i've tried auto refresh and it does not seem to reload JS and/or display text file's content)
Create Text file/Read/Display content/Refresh and/or Reload - no user refresh
<script>
function createFile()
{
var object = new ActiveXObject("Scripting.FileSystemObject");
var file = object.CreateTextFile("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", false);
file.WriteLine('Hello World');
file.WriteLine('Hope is a thing with feathers, that perches on the soul.');
file.Close();
}
</script>
this will not accomplished by using client side javascript only you have to use server side code:
server ex (using node.js):
server :
var http = require("http"),
fs=require("fs");
http.createServer(function(request, response) {
fs.writeFileSync("C:/Documents and Settings/galimbek.sagidenov/My Documents/Practice HTML_Photoshop_java/BroadcastTest.txt", 'Hello World\r\nHope is a thing with feathers, that perches on the soul.');
}).listen(8888);
client
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function(){
$.get("http://localhost:8888",function(){
console.log("writing to file successeded");
})
})
</script>

Google Chrome - download attribute of anchor tags

I've an extension which saves some files to the downloads folder. The code below is just for testing
//This lies in the background page of my extension
function fileTest(name) {
var a = document.createElement('a');
a.href = 'data:text/plain;base64,SGVsbG8gV29ybGQh'; //Hello World!
a.download = name + '.txt';
a.onclick = function (e) {console.log('[TEST] ' + name);return true;};
a.click();
}
window.onload = function() {
fileTest('test1');
fileTest('test12');
fileTest('test123');
}
only the first file "test1.txt" is saved to the disk, although the output of the console shows that there was 3 clicks
[TEST] test1
[TEST] test12
[TEST] test123
Is this an intentional limitation by the browser ? or there's something wrong with the code ?
When I run your code in a regular browsing session, I get a slide out notification (at the top of the window) that says
This site is attempting to download multiple files. Do you want to allow this?
So, yes, it is a security limitation of the browser to restrict downloads that are not user-initiated. You probably don't see the notification because the action is being performed by your background page.
The limitation seems to be one download per user action as demonstrated in this variant of your code:
window.onclick = function() {
fileTest('test1');
}
This will allow unlimited downloads, but only one download per click event.

path problem when using sub directories

I am working on a site where i have arranged my pages in directories except for the index page. My problem occurs when i use jquery to append images to a div within a section of the pages. It shows on the index page but not on other pages (which are directories). I understand why but not sure how i can fix it.
Is there a way to fix this without having to remove my other files from directories?
var $img1 = $('<img src="images/test1.jpg" />');
var $img2 = $('<img src="images/test2.jpg" />');
$('#container').append($img1, $img2);
Please note that the above code is also in a separate directory
Assuming that your images folder is located within the root directory of your website, you could just make the src attribute root-relative:
var $img1 = $('<img src="/images/test1.jpg" />');
var $img2 = $('<img src="/images/test2.jpg" />');
$('#container').append($img1, $img2);
(Note the / added to the beginning of the src attribute).
Reference:
Having links relative to root? (Apologies for any percieved self-promotion, but it was the first Google result here on Stackoverflow for my search for "root-relative url site:stackoverflow.com").
You can write the full link including domain name: var $img1 = $('<img src="http://www.yoursitename.com/images/test1.jpg" />');

How to set name of file downloaded from browser?

I'm writing a web application that, among other things, allows users to upload files to my server. In order to prevent name clashes and to organize the files, I rename them once they are put on my server. By keeping track of the original file name I can communicate with the file's owner without them ever knowing I changed the file name on the back end. That is, until they go do download the file. In that case they're prompted to download a file with a unfamiliar name.
My question is, is there any way to specify the name of a file to be downloaded using just HTML? So a user uploads a file named 'abc.txt' and I rename it to 'xyz.txt', but when they download it I want the browser to save the file as 'abc.txt' by default. If this isn't possible with just HTML, is there any way to do it?
When they click a button to download the file, you can add the HTML5 attribute download where you can set the default filename.
That's what I did, when I created a xlsx file and the browser want to save it as zip file.
Download
Download Export
Can't find a way in HTML. I think you'll need a server-side script which will output a content-disposition header. In php this is done like this:
header('Content-Disposition: attachment; filename="downloaded.pdf"');
if you wish to provide a default filename, but not automatic download, this seems to work.
header('Content-Disposition: inline; filename="filetodownload.jpg"');
In fact, it is the server that is directly serving your files, so you have no way to interact with it from HTML, as HTML is not involved at all.
just need to use HTML5 a tag download attribute
codepen live demo
https://codepen.io/xgqfrms/full/GyEGzG/
my screen shortcut.
update answer
whether a file is downloadable depends on the server's response config, such as Content-Type, Content-Disposition;
download file's extensions are optional, depending on the server's config, too.
'Content-Type': 'application/octet-stream',
// it means unknown binary file,
// browsers usually don't execute it, or even ask if it should be executed.
'Content-Disposition': `attachment; filename=server_filename.filetype`,
// if the header specifies a filename,
// it takes priority over a filename specified in the download attribute.
download blob url file
function generatorBlobVideo(url, type, dom, link) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function(res) {
// console.log('res =', res);
var blob = new Blob(
[xhr.response],
{'type' : type},
);
// create blob url
var urlBlob = URL.createObjectURL(blob);
dom.src = urlBlob;
// download file using `a` tag
link.href = urlBlob;
};
xhr.send();
}
(function() {
var type = 'image/png';
var url = 'https://cdn.xgqfrms.xyz/logo/icon.png';
var dom = document.querySelector('#img');
var link = document.querySelector('#img-link');
generatorBlobVideo(url, type, dom, link);
})();
https://cdn.xgqfrms.xyz/HTML5/Blob/index.html
refs
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#download
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#important_mime_types_for_web_developers
Sometimes #Mephiztopheles answer won't work on blob storages and some browsers.
For this you need to use a custom function to convert the file to blob and download it
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
}
Same code as #Hillkim Henry but with a.remove() improvement
This forces the document to remove the a tag from the body and avoid multiple elements
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
// Remove "a" tag from the body
a.remove()
}
Well, #Palantir's answer is, for me, the most correct way!
If you plan to use that with multiple files, then i suggest you to use (or make one) PHP Download Manager.
BUT, if you want to make that to one or two files, I will suggest you the mod_rewrite option:
You have to create or edit your .htaccess file on htdocs folder and add this:
RewriteEngine on
RewriteRule ^abc\.txt$ xyz.txt
With this code, users will download xyz.txt data with the name abc.txt
NOTE: Verify if you have already the "RewriteEngine on " on your file, if yes, add only the second for each file you wish to redirect.
Good Luck ;)
(Sorry for my english)