728x90
반응형
참고 stackoverflow
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<a id='a1' href="https://image.shutterstock.com/image-photo/colorful-flower-on-dark-tropical-260nw-721703848.jpg"
download='asdfa.webp'>다운로드</a>
<script>
function MS_bindDownload(el) {
if (el === undefined) {
throw Error('I need element parameter.');
}
if (el.href === '') {
throw Error('The element has no href value.');
}
var filename = el.getAttribute('download');
console.log("filename : " ,filename);
if (filename === null){
throw Error('I need download property.');
}
if (filename === '') {
var tmp = el.href.split('/');
filename = tmp[tmp.length - 1];
}
el.addEventListener('click', function (evt) {
evt.preventDefault(); //href로 이동을 막음
var xhr = new XMLHttpRequest();
xhr.onloadstart = function () {
xhr.responseType = 'blob';
};
xhr.onload = function () {
navigator.msSaveBlob(xhr.response, filename);
};
xhr.open("GET", el.href, true);
xhr.send();
})
}
let element = document.querySelector('a');
if (window.navigator.msSaveBlob){
MS_bindDownload(element);
}
</script>
</body>
</html>
728x90
반응형
'javascript' 카테고리의 다른 글
[javascript] object에서 key값에 접근할 때 오류, object[" "]형식으로 접근하기 (0) | 2021.10.22 |
---|---|
JavaScript Closures MDN 예제 해석 (0) | 2021.09.10 |
JavaScript closure 개념 (0) | 2021.09.10 |
인턴의 첫번째 과제 코드 리뷰 (0) | 2021.09.10 |
function과 function()의 차이, onclikc=function과 onclick=function()의 차이 (0) | 2021.08.19 |