How do I initialize an automatic download of a file in Internet Explorer?
For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads.
In Firefox this is easy, you just need to include a meta tag in the header, <meta http-equiv="Refresh" content="n;url"> where n is the number of seconds and url is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?
SourceForge uses an <iframe> element with the src="" attribute pointing to the file to download.
<iframe width="1" height="1" frameborder="0" src="[File location]"></iframe>
(Side effect: no redirect, no JavaScript, original URL remains unchanged.)
I hate when sites complicate download so much and use hacks instead of a good old link.
Dead simple version:
Start automatic download!
It works! In every browser!
If you want to download a file that is usually displayed inline (such as an image) then HTML5 has a download attribute that forces download of the file. It also allows you to override filename (although there is a better way to do it):
Download
Version with a "thanks" page:
If you want to display "thanks" after download, then use:
<a href="file.zip"
onclick="if (event.button==0)
setTimeout(function(){document.body.innerHTML='thanks!'},500)">
Start automatic download!
</a>
Function in that setTimeout might be more advanced and e.g. download full page via AJAX (but don't navigate away from the page — don't touch window.location or activate other links).
The point is that link to download is real, can be copied, dragged, intercepted by download accelerators, gets :visited color, doesn't re-download if page is left open after browser restart, etc.
That's what I use for ImageOptim
I recently solved it by placing the following script on the page.
setTimeout(function () { window.location = 'my download url'; }, 5000)
I agree that a meta-refresh would be nicer but if it doesn't work what do you do...
I had a similar issue and none of the above solutions worked for me. Here's my try (requires jquery):
$(function() {
$('a[data-auto-download]').each(function(){
var $this = $(this);
setTimeout(function() {
window.location = $this.attr('href');
}, 2000);
});
});
Usage: Just add an attribute called data-auto-download to the link pointing to the download in question:
<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="/your/file/url">here</a>.</p>
It should work in all cases.
A simple bit of jQuery solved this problem for me.
$(function() {
$(window).bind('load', function() {
$("div.downloadProject").delay(1500).append('<iframe width="0" height="0" frameborder="0" src="[YOUR FILE SRC]"></iframe>');
});
});
In my HTML, I simply have
<div class="downloadProject"></div>
All this does is wait a second and a half, then append the div with the iframe referring to the file that you want to download. When the iframe is updated onto the page, your browser downloads the file. Simple as that. :D
I used this, seems working and is just simple JS, no framework:
Your file should start downloading in a few seconds.
If downloading doesn't start automatically
<a id="downloadLink" href="[link to your file]">click here to get your file</a>.
<script>
var downloadTimeout = setTimeout(function () {
window.location = document.getElementById('downloadLink').href;
}, 2000);
</script>
NOTE: this starts the timeout in the moment the page is loaded.
Works on Chrome, firefox and IE8 and above:
var link = document.createElement('a');
document.body.appendChild(link);
link.href = url;
link.click();
This is what I'm using in some sites (requires jQuery).:
$(document).ready(function() {
var downloadUrl = "your_file_url";
setTimeout("window.location.assign('" + downloadUrl + "');", 1000);
});
The file is downloaded automatically after 1 second.
I checked and found, it will work on button click via writing onclick event to Anchor tag or Input button
onclick='javascript:setTimeout(window.location=[File location], 1000);'
Back to the roots, i use this:
<meta http-equiv="refresh" content="0; url=YOURFILEURL"/>
Maybe not WC3 conform but works perfect on all browsers, no HTML5/JQUERY/Javascript.
Greetings Tom :)
One more :
var a = document.createElement('a');
a.setAttribute('href', dataUri);
a.setAttribute('download', filename);
var aj = $(a);
aj.appendTo('body');
aj[0].click();
aj.remove();
I hope this will works all the browsers. You can also set the auto download timing.
<html>
<head>
<title>Start Auto Download file</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('a[data-auto-download]').each(function(){
var $this = $(this);
setTimeout(function() {
window.location = $this.attr('href');
}, 2000);
});
});
</script>
</head>
<body>
<div class="wrapper">
<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="auto-download.zip">here</a>.</p>
</div>
</body>
</html>
Be sure to serve up the file without a no-cache header! IE has issues with this, if user tries to "open" the download without saving first.
This seemed to work for me - across all browsers.
<script type="text/javascript">
window.onload = function(){
document.location = 'somefile.zip';
}
</script>
For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers.
I had trouble in IE10+ downloading a PDF and used #dandavis' download function (https://github.com/rndme/download).
IE10+ needs msSaveBlob.
I think this will work for you. But visitors are easy if they got something in seconds without spending more time and hence they will also again visit your site.
<a href="file.zip"
onclick="if (event.button==0)
setTimeout(function(){document.body.innerHTML='thanks!'},500)">
Start automatic download!
</a>
Nice jquery solution:
jQuery('a.auto-start').get(0).click();
You can even set different file name for download inside <a> tag:
Your download should start shortly. If not - you can use
direct link.
<meta http-equiv="Refresh" content="n;url">
That's It. Easy, Right?
<meta http-equiv="Refresh" content="n;url">
This is an old question but in case anyone wants to use automatic download of files with Flask, Python. You can do this:
from flask import Flask, make_response, send_from_directory
file_path = "Path containing the file" #e.g Uploads/images
#app.route("/download/<file_name>")
def download_file(file_name):
resp = make_response(send_from_directory(file_path, file_name)
resp.headers['Content-Disposition'] = f"attachment; filename={file_name}"
return resp
Inside a template or html page, index for example
<div>
<a class="btn btn-outline-warning" href={{url_for( 'download_file', name='image.png' )}} ">Download Image</a>
</div>
Clicking on the link will download the file without opening another page.
For more info on:
Content-Disposition
Setting request headers in Flask
Related
I have a real .php page like this http://hiteachers.com/soccer_parse.php?id=5. I want to add it into a blogger.com new page (**not a new blog post, or new HTML widget **, and I've got this successfully.
https://tranbongda.blogspot.com/p/function-myfunction-window.html
I used the code like this:
<script>
var Window;
// Function that open the new Window
function windowOpen() {
Window = window.open("http://hiteachers.com/soccer_parse.php?id=5",
"_blank", "width=400, height=450");
}
// function that Closes the open Window
function windowClose() {
Window.close();
}
</script>
<button onclick="windowOpen()">Open page</button>
<button onclick="windowClose()">Close page</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
$(document).ready(function()
$("button").click(function(){
$("#div1").load("http://hiteachers.com/soccer_parse.php?id=5");
});
});
</script>
My expectation is that I'd like the blogger page to load the original content of the .php page immediately when the visitor visits the blogger.com page (https://tranbongda.blogspot.com/p/function-myfunction-window.html) without clicking on any button.
I have thought of creating iframe by using this:
<iframe name="Framename" src="http://hiteachers.com/soccer_parse.php?id=5" width="550" height="550" frameborder="0" scrolling="yes" style="width: 100%;"> </iframe>
But the blogger.com page does not accept it, and returns the error message like this:
This page contains HTTP resources which may cause mixed content affecting security and user experience if blog is viewed over HTTPS.
Then I moved to try this <object width="500" height="300" type="text/html" data="http://hiteachers.com/soccer_parse.php?id=5"></object> as per some bloggers' suggestions, but I still failed.
Some other bloggers suggested to use AJAX, which is very new to me.
So, is there any way to parse the provided .php page content and add it to the blogspot.com/blogger.com new page without showing the url of the .php page or window pop-ups?
Can you help me please?
Thanks
As the bloggers likely have suggested, make the PHP server a REST endpoint and access the data on the blog site with Asynchronous JavaScript and XML. Although today people have tended to scratch the XML part and go with JSON or something.
AJAX is accomplished by using the XMLHttpRequest object.
Mozilla's spec provides links and stuff which will show you how to use it
and w3schools is a good resource.
Then it's all comes down to editing the page directly
element.removeChild(element.lastChild);
element.appendAdjacentHTML('beforeend',xhr.responseText);
I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});
I require to preview PDF file stored in database. In Chrome its working fine but when i do it in IE it gets downloaded. Reason may be due to below code:
Javascript Method:
if (navigator.appVersion.toString().indexOf('.NET') > 0) {
console.log(response._body);
window.navigator.msSaveBlob(response._body, obj.documentName);
}
Controller Method:
[HttpGet]
public FileResult DownLoadFile(int id)
{
List<FileDetailsModel> ObjFiles = GetFileList();
var FileById = (from FC in ObjFiles
where FC.Id.Equals(id)
select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();
return File(FileById.FileContent, "application/pdf", FileById.FileName);
}
So is there way by which we can preview PDF file as all files are in PDF format in database.
A solution (that is surely not the best because iframe are deprecated) would be make an intermediate page framed to occupy 100% of parent page like :
<html>
<body>
<iframe src="#Url.Action("DownLoadFile", new {id = 1})" width="100%" height="100%" />
</body>
</html>
I have this snippet for you where we check browsers. I think you can use parts of it to fix your problem. Cross-browser file serving through javascript is sometimes a PITA.
use GGO's iframe suggestion but to generate the url use this code:
var fileURL = URL.createObjectURL(file);
I got solution for this. I converted word, excel and pdf documents in html version using SaveOptions in aspose and then can easily render html output in div or new window in IE
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="gistfile1.js"></script>
</head>
<body>
<p id="divPDF">Can't see the PDF?</p>
</body>
<script type="text/javascript">
var info = getAcrobatInfo();
if (info.acrobat == false){
window.location = "empty.pdf";
} else {
document.getElementById("divPDF").innerHTML = "<object data='empty.pdf' type='application/pdf' width='100%' height='100%'><p class='helpContent'>Can't see the PDF? Try <a href='empty.pdf' download='empty.pdf'>downloading the file</a>. If you're still having trouble, <a href='/contactUs.jsp'>contact us</a> or email us directly at <a href='mailto:support#guitarinstructor.com'>support#guitarinstructor.com</a>.</p></object>";
}
</script>
</html>
Here's what I'm looking at doing. IF the getAcrobatInfo TRUE, display the PDF.
If the getAcrobat returns FALSE, then automatically download the PDF.
I thought this would work on a window.location = "URL OF THE PDF", my browser still attempts to display it.
Is there any javascript or jQuery that I can implement that will allow me to force an auto download if the user's browser doesn't have a PDF Reader plugin?
Typically you must set the Content-disposition header to attachment to encourage a browser to download a file instead of displaying it. If you can do this, and your client side plugin detection works, you could edit your server side code to have a different URL depending on the disposition you want to send, and have that in your object src attribute or location.replace argument.
Additionally, in HTML5 there is a download attribute for the <a> tag, with an optional filename as the attribute value. Support for this is not in every browser.
Download
Note that a very common practice is to have a single link with a small blurb informing a user how to download a file (e.g. using the right mouse button).
how do i redirect to a welcome page from an index page using javascript?
The site is offline and on a development machine and not in a server www directory like (wamp, lamp, apache etc) . I would like to do it without using PHP, python etc cause I already know how it is done in php using header(location ... ).
The directory structure
site
|
|--img
|--css
|--index.html
|--welcome.html
|--error.html
I have already tried window.location, window.location.href etc.
Inside the script of index.html.
if (true){
self.location("welcome.html");
}
else{
window.location.href = "error.html";
}
Though Window.location is a read-only Location object, you can also
assign a DOMString to it. This means that you can work with
window.location as if it were a string in most cases: window.location
= 'http://www.example.com' is a synonym of window.location.href = 'http://www.example.com'.
Mozilla Docs -- Window.location
It is not a function but you can assign a string to it.
Just write:
window.location="error.html";
self.location="error.html"; is fine too
You could also use a meta-refresh redirect:
<meta http-equiv="refresh" content="0;URL='welcome.html" />
Or just do window.location="welcome.html" instead of self.location("welcome.html")
``This is very simple to do a page redirect using JavaScript at client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows:
<head>
<script type="text/javascript">
<!--
window.location="http://www.newlocation.com";
//-->
</script>
</head>
Thanks for all your advice.
But I was able to do it myself using window.location method. I found that the method was not the problem because I had tried it already previously.
The problem was that the redirection happened but since the function "checkLogin" was called by the onsubmit function of html element form,
it kept coming back to the same login page.
I fixed it by returning false at the end of the checkLogin() script.
But Thanks a ton for all your input.