Home > Web Front-end > JS Tutorial > How to download files to local through js code? (example)

How to download files to local through js code? (example)

藏色散人
Release: 2019-08-20 14:08:09
Original
14188 people have browsed it

There are many ways to download files. This article will introduce you to several simple operations on how to use js to download files to your local computer. Hope it helps friends in need. The usual download method, for example, the address to download the file is: http://127.0.0.1/demo.rar.

The specific code example of js local download file is as follows:

1. This method has no effect on Firefox, but it works on IE browser

window.open("htpp://127.0.0.1/demo.rar");
Copy after login

2. This method is not supported by some versions of Firefox

window.location.href="htpp://127.0.0.1/test.rar";
Copy after login

3. In order to solve the problem Some versions of Firefox do not support it, you can change it to this method

window.location="htpp://127.0.0.1/demo.rar";
Copy after login

How to download files to local through js code? (example)

4. This method can be used by IE and Firefox. The url indicates the path of the file to be downloaded:

htpp://127.0.0.1/demo.rarfunction downloadFile(url) {   
   try{ 
        var elemIF = document.createElement("iframe");   
        elemIF.src = url;   
        elemIF.style.display = "none";   
        document.body.appendChild(elemIF);   
    }catch(e){ 
        zzrw.alert("下载异常!");
    }     
}
Copy after login

5. Directly download the file in form mode. The url indicates the path of the file to be downloaded:

htpp://127.0.0.1/demo.rarfunction downloadFile(url){
    var form=$("<form>");
    form.attr("style","display:none");
    form.attr("target","");
    form.attr("method","get"); 
    form.attr("action",url);
    $("body").append(form);
    form.submit();//表单提交}
Copy after login

Note:

var form=$("

");Define the form form , Send a request through the form

orm.attr(); Set to not display

form.attr(); Set the request type

form.attr() ;Set the request path

$("body").append(form);Add the form to the page (body)

form.submit();Form submission

The above is the detailed content of How to download files to local through js code? (example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template