티스토리 글에서 file download 버튼 만들기

티스토리에서 글을 작성할 때,

url 링크는 해당창에서 열리거나 링크버튼에서 "새창으로 띄우기" 옵션을 선택해서 접근할 수 있습니다.

 

이 때 zip파일이나 사이트 주소가 아니면 대부분 정상적으로 다운로드하여 사용하는데 문제가 없지만, 간혹 인터넷 창에서 바로 열리는 파일들은 다운을 받으려고 걸어둔 링크가 정상작동하지 않고 그 내용이 보이는 경우가 있습니다.

 

이 때엔 아래처럼 링크주소를 입력하거나 버튼을 만드는 것이 아니라 "자바스크립트" 를 추가하여 정상적으로 작동하게끔 만들어 주면 됩니다.

 

 

다운받고자 하는 url

https://raw.githubusercontent.com/OfficeDev/Office-Add-in-samples/main/Samples/office-add-in-commands/excel/manifest.xml

 

 

javascript를 적용한 다운로드버튼 

 

 

인터넷에서 찾은 target을 이용하는 방법은 적용불가

Download Not Available

 

 

 

 

 

===========(글을 작성할 때는, 아래 캡쳐처럼 "SCRIPT"라는 창이 별도로 보입니다 ========

 

 

 

 

===== 적용한 소스코드 ====

<button id="hw">Download</button>
<script type="text/javascript">
  var hw = document.getElementById('hw');

  hw.addEventListener('click', function () {
    // Usage: Call the `downloadRawFile` function with the raw file URL
    const rawFileUrl = 'https://raw.githubusercontent.com/OfficeDev/Office-Add-in-samples/main/Samples/office-add-in-commands/excel/manifest.xml';
    downloadRawFile(rawFileUrl);
  })

  function downloadRawFile(url) {
    fetch(url)
      .then(response => response.blob())
      .then(blob => {
        // Create a temporary link element
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = getFileNameFromUrl(url);

        // Simulate a click on the link element to trigger the download
        link.click();

        // Clean up the temporary link
        URL.revokeObjectURL(link.href);
      })
      .catch(error => {
        console.error('Error:', error);
      });
  }

  function getFileNameFromUrl(url) {
    // Extract the file name from the URL
    const parts = url.split('/');
    return parts[parts.length - 1];
  }
</script>

 

 

 

 

=end

반응형