javascript - Download file on button click jquery - Stack Overflow

Simple question, i think.I have an html button: <button type="button" class="btn btn

Simple question, i think.

I have an html button: <button type="button" class="btn btn-success">Download</button>.

On click i have to start the download of a file placed in the same folder as the project. I've never used anything to download a file so i have no clue how to do it and i'm not understanding from other question either. Could someone tell me how to do it explaining why i have to do it in a certain way? All of this should be preferable in jquery, but even basic js is fine. Thanks.

Simple question, i think.

I have an html button: <button type="button" class="btn btn-success">Download</button>.

On click i have to start the download of a file placed in the same folder as the project. I've never used anything to download a file so i have no clue how to do it and i'm not understanding from other question either. Could someone tell me how to do it explaining why i have to do it in a certain way? All of this should be preferable in jquery, but even basic js is fine. Thanks.

Share Improve this question asked Jun 8, 2022 at 7:47 Filippo CaninoFilippo Canino 131 silver badge6 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

using <a> does the job without involving javascript

<a href="./file-path/file-name" class="btn btn-success" download>Download</a>

The download attribute will force download the viewable content. Otherwise, It will be rendered instead of downloading.

Indeed should do the work for you. To better understand the functionality think of the following function

function DownloadUsingAnchorElement(fileUrl, fileName)
{
  const anchor = document.createElement("a");
  anchor.href = fileUrl;
  anchor.download = fileName;
  document.body.appendChild(anchor);
  anchor.click();
  document.body.removeChild(anchor);
}

Check as well : https://www.w3schools./tags/att_a_download.asp

document.querySelector('button').addEventListener('click', () => {
  const link = document.createElement('a')
  link.setAttribute('download', 'filename')
  link.setAttribute('href', './path-to-file/filename.ext')
  link.click()
})

you can also do this way

<button type="button" class="btn btn-success" id="downloadButton">Download</button>

$(document).ready(function () {
      $("#downloadButton").click(function (e) {
          e.preventDefault();
          window.location.href = "your file path";
      });
});


发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744886377a4599144.html

相关推荐

  • javascript - Download file on button click jquery - Stack Overflow

    Simple question, i think.I have an html button: <button type="button" class="btn btn

    1天前
    70

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信