HOWTO · jQuery

jQuery 다운로드 파일

이 튜토리얼은 jQuery를 사용하여 파일을 다운로드하는 방법을 보여줍니다.

이 페이지의 내용

이 튜토리얼은 jQuery를 사용하여 파일을 다운로드하는 방법을 보여줍니다.

jQuery 다운로드 파일

jQuery를 사용하여 JavaScript 및 HTML과 동일한 기능을 가진 파일을 다운로드할 수도 있습니다. jQuery와 함께 HTML 앵커 태그를 사용하여 파일을 다운로드할 수 있습니다.

단계별 프로세스를 살펴보겠습니다.

  • 먼저 소스 #을 사용하여 HTML에서 앵커 태그를 만듭니다.
  • DOM이 로드될 때 다운로드를 수행할 수 있도록 ready() 메서드를 만듭니다.
  • ready() 메서드 내에서 앵커 태그를 대상으로 하는 click 이벤트를 만듭니다.
  • 오류를 preventDefault로 설정합니다.
  • 마지막으로 앵커 태그의 href를 다운로드할 파일의 경로로 설정합니다.
  • 시스템을 실행하고 링크를 클릭합니다. 파일이 다운로드됩니다.

위의 단계를 기반으로 예제를 구현해 보겠습니다.

<!DOCTYPE html>
<html>

<head>
    <title>JQuery Downalod File</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <style>
    #Main {
            border: 5px solid green;
            background-color : lightblue;
            height: 10%;
            width:  20%;
        }
</style>
</head>

<body>
<div id = "Main">
    <h1>Download File Using jQuery </h1>

    <h3>Click the link do download the file..</h3>

    <a id="download" href="#">    Download this file</a>

    <script>
        $(document).ready(function () {
            $("#download").click(function (e) {
                e.preventDefault();
                window.location.href = "delftstack.docx";
            });
        });
    </script>
<div>
</body>
</html>

위의 코드는 클릭 시 파일을 다운로드합니다. 출력을 참조하십시오.

jQuery를 사용하여 파일 다운로드

보시다시피 window.location.href = "delftstack.docx";를 사용했습니다. 다운로드할 파일의 경로를 설정합니다. 여기에서 attr()을 사용하여 href 속성을 경로로 설정할 수도 있습니다.

다른 예를 참조하십시오.

<!DOCTYPE html>
<html>

<head>
    <title>JQuery Downalod File</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <style>
    #Main {
            border: 5px solid green;
            background-color : lightblue;
            height: 10%;
            width:  20%;
        }
</style>
</head>

<body>
<div id = "Main">
    <h1>Download File Using jQuery </h1>

    <h3>Click the link do download the file..</h3>

    <a id="download" href="#">    Download this file</a>

    <script>
        $(document).ready(function () {
            $("#download").click(function (e) {
                $("#download").attr({target: '_blank', href : "delftstack.docx"})
            });
        });
    </script>
<div>
</body>
</html>

이제 코드는 attr 메서드를 사용하여 지정된 경로에서 파일을 다운로드합니다. 출력을 참조하십시오.

jQuery 속성을 사용하여 파일 다운로드