WEB/JS
누구나 할 수있는 자바스크립트에서 이미지 다운로드하기
나나나나나나나ㅏ나난ㄴ나ㅏ나나
2022. 12. 28. 18:56
728x90
AWS S3에 올려둔 이미지를 다운로드해보자!
우선 코드 먼저
let image = new Image();
image.onload = function() {
const canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
const ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0);
let dataURL = canvas.toDataURL();
const element = document.createElement('a');
element.setAttribute('href', dataURL);
element.setAttribute('download', '이미지 다운로드 완료');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
image.crossOrigin = "Anonymous";
image.width = 1500
image.height = 1500;
image.src = `${image_url}?not-from-cache-please`;
간단하게 설명하면
1. AWS URL 로 이미지 파일 만들기
2. 이미지 파일에서 BASE 64 추출하기
3. a 태그의 element 만들어서 다운로드 사용하기
이렇게 하면
짜잔 다운로드 완료 !
지금까지는 귀찮아서 그냥 해당 URL 로 이동하게 했는데,
생각보다 간단하게 완료할 수 있었다

앞으로는 URL 이동말고 다운로드 폴더에 조심스레 넣어줘야겠다
✋잠깐 혹시 AWS 파일 만들때 CORS 오류가 발생한다면?
2022.11.23 - [WEB/JS] - 이미지 가져올때 CORS 오류가 발생한다....!!!!! [AWS S3+CDN]
728x90