How to make a field to download the file?

Closed due to the fact that the question is too common for the participants Enikeyschik , LFC , andreymal , Air , aleksandr barakin 27 Feb at 0:07 .

Please correct the question so that it describes the specific problem with sufficient detail to determine the appropriate answer. Do not ask a few questions at once. See “How to ask a good question?” For clarification. If the question can be reformulated according to the rules set out in the certificate , edit it .

    2 answers 2

    if you need to download the file from the server, it is done like this:

    <a href="%file_URL%">download</a> 

    If you need a field, it is done like this:

     <textarea id="file_here"></textarea> 

    the file is pushed into it like this:

     document.getElementById('file_here').innerHTML = %file_content% 

    Of course, displaying content in innerHTML may not be normally done for all data, but only for text. therefore, it is possible not to make a field, but a link or button, on clicking on which a function will be called that loads a file, for example, such (moderators, don't hit, I don’t remember where I found this function, but I’ve been using it for a long time)

     /** * Инициирует загрузку файла * @param {string} filename - имя загружаемого файла * @param {string} data - данные в файле */ function downloadFile(filename, data) { var a = document.createElement('a'); a.style = "display: none"; var blob = new Blob([data], {type: "application/octet-stream"}); var url = window.URL.createObjectURL(blob); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); window.setTimeout(() => { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 2000); } 

    Of course, the data (% file_content% for textarea and data for the downloadFile function must be generated in advance, for example, in javascript)

      The file must be on the same domain.

       <a href="smth.pdf" download>Download</a>