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

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

藏色散人
藏色散人Original
2018-08-14 16:15:0514133browse

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");

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

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

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";

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("下载异常!");
    }     
}

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();//表单提交}

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!

Statement:
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