How to Force Download with HTML/JavaScript

Force download through js or query

You can not force that behavior from JavaScript, the HTTP Headers need to be set on the server side:

Content-disposition=attachment; filename=some.file.name

The way you can solve the problem is to let your AJAX method redirect the user to the URL of the PDF:

location.replace('path/to.pdf');

(The above HTTP headers must be set for the PDF)


Update

At the time of this answer, it wasn't possible. Now it is, scroll down to see the other answer saying so.

How do I force download with HTML/JavaScript?

Automatically will depend a lot on the browser and its options. But you can tell the browser what you want to have happen (which it will then double-check with the user) via the Content-Disposition header in the response. For instance, setting it to attachment;filename=blah.mp4 will, on most browsers, invite the user to download it (using that filename) even if normally the browser would have tried to display/play the content in its own interface. See the link for details. (Downloading is probably the default for mp4 files, but that's up to the user; I find this helpful when offering download links for HTML files.)

You can set the header via configuration in your web server if you're not using server-side scripting (as you've said you're not). For instance, with Apache you'd use a rule matching the URL for these video files and use the Header directive.

How to trigger a file download when clicking an HTML button or JavaScript

For the button you can do

<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>

How to force the browser to download only part of an audio/video element?

Try this:

const mediaElement = document.querySelector("#myMediaElementID");
mediaElement.removeAttribute("src");
mediaElement.load();

By removing the media element's src attribute and invoking the load() method, you release the resources associated with the audio/video, which stops the network download. You must call load() after removing the attribute, because just removing the src attribute does not invoke the load algorithm.

https://developer.mozilla.org/en-US/docs/Web/Guide/Audio_and_video_delivery

Force the browser to download an Html Page instead of rendering it

You can do the following trick. You create a <a> tag and you give him a custom object URL as its href attribute.

This will cause the <a> to force download with the mimetype set.

You can put your HTML in the content variable.

var name ='excel-file.xlsx';  // The name of the file to be downloaded
var content = 'data'; // The contents of the file
var mimetype = 'application/vnd.ms-excel'; // The mimetype of the file for the browser to handle

// Add the <a> in the end of the body. Hide it so that it won't mess with your design.
$('body').append('<a class="download-trigger" style="display:none;"></a>');

var a = $('.download-trigger')[0];
a.href = window.URL.createObjectURL(new Blob([content], {
type: mimetype
}));
a.download = name;
a.textContent = 'Download';
a.click();

Note: You only need to append the <a> to the <body> only once, not every time you execute this code.

Here is a demo http://jsfiddle.net/5dyunv6w/ (download will start when you open the page)

How do I force download with html/javascript in a jsp from IE 9 and above?

You can create a JSP and use it as a servlet. It'll recieve a link by parameter with the url of image that you want download.

This servlet will open a stream to read the file and other stream to write the output on your browser. With this your browser will be responsable to handling your file.

Follow a example of this JSP.

<%@ page language="java" contentType="image/jpeg; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String urlPrefix = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();

String fileUrl = request.getParameter("fileUrl");
if (fileUrl == null || "".equals(fileUrl.trim())) {
throw new Exception("No image Found.");
}

String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);

response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode(fileName, "UTF-8"));

String fullEncodedUrl = urlPrefix + URIUtil.encodePath(fileUrl);

URL url = new URL(fullEncodedUrl);

URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();

BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ((len = stream.read(buf)) > 0) {
outs.write(buf, 0, len);
}
outs.close();
%>

Download File Using JavaScript/jQuery

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

In jQuery:

$('a#someID').attr({target: '_blank', 
href : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.



Related Topics



Leave a reply



Submit