AJAX로 직접 파일을 받아서 쓰는 건 생각보다 훨씬 유용하지 않을 수 없당.
잘 쓰지 못해서 안 쓸 뿐, 이번 기회에 정리해서 다시는 날개를 접지 말장
sample1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>E7E E7E</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.8.4/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<script>
// 샘플 이미지 주소 내 맘은 카리나
const testURL = "https://media.nudge-community.com/8227404";
// AXIOS
async function axiosFileDownload(url) {
const resp = await axios.get(url, { responseType: "blob" });
let aTag = document.createElement("a");
aTag.href = URL.createObjectURL(resp.data);
aTag.download = "axios.gif";
aTag.click();
}
axiosFileDownload(testURL);
//FETCH
async function fetchFileDownload(url) {
const resp = await fetch(url);
let aTag = document.createElement("a");
aTag.href = URL.createObjectURL(await resp.blob());
aTag.download = "fetch.gif";
aTag.click();
}
fetchFileDownload(testURL);
// JQUERY AJAX
$.ajax({
url: testURL,
xhrFields: {
responseType: "blob",
},
success: (rslt) => {
let aTag = document.createElement("a");
aTag.href = URL.createObjectURL(rslt);
aTag.download = "jquery.gif";
aTag.click();
},
});
// Vanilla JS
function vanillaAjax() {
const xhr = new XMLHttpRequest();
xhr.open("get", testURL, true);
xhr.responseType = "blob";
xhr.onload = (rslt) => {
let aTag = document.createElement("a");
aTag.href = URL.createObjectURL(xhr.response);
aTag.download = "vanilla.gif";
aTag.click();
};
xhr.send();
}
vanillaAjax();
</script>
</body>
</html>
실행 해보면 자동으로 파일4개가 다운됨을 알수 있당.
[만약 console에 Cross-Origin 에러가 났다면 브라우져 플러그인 Cross-Origin을 실행하장
참고로 이 브라우져 플러그인은 그리 안정적이진 못하다 별 3개 반.]
위 코드는 자세히 보면 a 태그 만들고 하는 부분이 반복이 심하당.
이럴땐 머리에 DRY(Do not Repeat Yourself) 원칙 과
KISS(Keep It Simple, Stupid) 원칙이 생각나면 아름다운 후광이당.
사포로 조금 손질 좀 해보장.
sample2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>E7E 272</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.8.4/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<script>
// 샘플 이미지 주소 내 맘은 카리나
const testURL = "https://media.nudge-community.com/8227404";
// 공통 부분 함수화
function downBlob(blob, filename) {
console.log(`체킁 ${filename}`, blob);
let aTag = document.createElement("a");
aTag.href = URL.createObjectURL(blob);
aTag.download = filename;
aTag.click();
URL.revokeObjectURL(blob); // 권장 메모리에 남아있는 거 해제, 안 하는 사람 더 많음
}
// AXIOS
async function axiosFileDownload(url) {
const resp = await axios.get(url, { responseType: "blob" });
downBlob(resp.data, "axios1.gif");
}
axiosFileDownload(testURL);
//FETCH
async function fetchFileDownload(url) {
const resp = await fetch(url);
downBlob(await resp.blob(), "fetch1.gif");
}
fetchFileDownload(testURL);
// JQUERY AJAX
$.ajax({
url: testURL,
xhrFields: {
responseType: "blob",
},
success: (rslt) => {
downBlob(rslt, "jquery2.gif");
},
});
// Vanilla JS
function vanillaAjax() {
const xhr = new XMLHttpRequest();
xhr.open("get", testURL, true);
xhr.responseType = "blob";
xhr.onload = (rslt) => {
downBlob(xhr.response, "vanilla2.gif");
};
xhr.send();
}
vanillaAjax();
</script>
</body>
</html>
결과는 이전과 똑같지 않지 않을 이유를 찾을 수 없지 않지 않을 수 없더라.
아주 자주 서버에서 받은 파일을 바로 다운로드 시키지 않고
화면에 넣은 다음 클릭시 다운로드를 해줘야 할 때가 분명 없지 않지 않다.
소스 맨끝에 덤으로 넣었당.
sample3.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.8.4/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<div id="disp"></div>
<script>
const disp = document.querySelector("#disp");
// 샘플 이미지 주소 내 맘은 카리나
const testURL = "https://media.nudge-community.com/8227404";
function downBlob(blob, filename) {
console.log(`체킁 ${filename}`, blob);
let aTag = document.createElement("a");
aTag.href = URL.createObjectURL(blob);
aTag.download = filename;
aTag.click();
URL.revokeObjectURL(blob); // 권장 메모리에 남아있는 거 해제, 안 하는 사람 더 많음
}
// AXIOS
async function axiosFileDownload(url) {
const resp = await axios.get(url, { responseType: "blob" });
downBlob(resp.data, "axios3.gif");
}
axiosFileDownload(testURL);
//FETCH
async function fetchFileDownload(url) {
const resp = await fetch(url);
downBlob(await resp.blob(), "fetch3.gif");
}
fetchFileDownload(testURL);
// JQUERY AJAX
$.ajax({
url: testURL,
xhrFields: {
responseType: "blob",
},
success: (rslt) => {
downBlob(rslt, "jquery3.gif");
},
});
// Vanilla JS
function vanillaAjax() {
const xhr = new XMLHttpRequest();
xhr.open("get", testURL, true);
xhr.responseType = "blob";
xhr.onload = (rslt) => {
downBlob(xhr.response, "vanilla3.gif");
};
xhr.send();
}
vanillaAjax();
// 이건 덤으로 다운받은 파일 화면에 넣고, 클릭하면 다운받깅
// 이건 1개만 axios를 이용해서
async function axiosDum(url) {
const resp = await axios.get(url, { responseType: "blob" });
const domUrlString = URL.createObjectURL(resp.data);
const imgTag = document.createElement("img");
imgTag.src = domUrlString;
imgTag.width = 300;
imgTag.height = 300;
imgTag.style.borderRadius = "50%";
const aTag = document.createElement("a");
aTag.href = domUrlString;
aTag.download = "메롱.gif";
aTag.appendChild(imgTag);
disp.appendChild(aTag);
}
axiosDum(testURL);
</script>
</body>
</html>
무언가 심심하단 느끼미가 연타로 나의 브레인을 재미없다 모략한당.
sample4.html (재미용 animation 추가, 이거시 최종버젼)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.8.4/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<style>
@keyframes jihyuni {
0% {
left: 5%;
transform: rotate(0deg);
}
50% {
left: 75%;
transform: rotate(360deg);
}
100% {
left: 5%;
transform: rotate(0deg);
}
}
img {
position: relative;
margin-top: 50px;
animation: jihyuni 10s ease 1s infinite alternate-reverse;
}
</style>
</head>
<body>
<div id="disp"></div>
<script>
const disp = document.querySelector("#disp");
// 샘플 이미지 주소 내 맘은 카리나
const testURL = "https://media.nudge-community.com/8227404";
function downBlob(blob, filename) {
console.log(`체킁 ${filename}`, blob);
let aTag = document.createElement("a");
aTag.href = URL.createObjectURL(blob);
aTag.download = filename;
aTag.click();
URL.revokeObjectURL(blob); // 권장 메모리에 남아있는 거 해제, 안 하는 사람 더 많음
}
// AXIOS
async function axiosFileDownload(url) {
const resp = await axios.get(url, { responseType: "blob" });
downBlob(resp.data, "axios.gif");
}
axiosFileDownload(testURL);
//FETCH
async function fetchFileDownload(url) {
const resp = await fetch(url);
downBlob(await resp.blob(), "fetch.gif");
}
fetchFileDownload(testURL);
// JQUERY AJAX
$.ajax({
url: testURL,
xhrFields: {
responseType: "blob",
},
success: (rslt) => {
downBlob(rslt, "jquery.gif");
},
});
// Vanilla JS
function vanillaAjax() {
const xhr = new XMLHttpRequest();
xhr.open("get", testURL, true);
xhr.responseType = "blob";
xhr.onload = (rslt) => {
downBlob(xhr.response, "vanilla");
};
xhr.send();
}
vanillaAjax();
// 이건 덤으로 다운받은 파일 화면에 넣깅
// 이거까정 알아두깅!
async function axiosDum(url) {
const resp = await axios.get(url, { responseType: "blob" });
const domUrlString = URL.createObjectURL(resp.data);
const imgTag = document.createElement("img");
imgTag.src = domUrlString;
imgTag.width = 300;
imgTag.height = 300;
imgTag.style.borderRadius = "50%";
const aTag = document.createElement("a");
aTag.href = domUrlString;
aTag.download = "메롱.gif";
aTag.appendChild(imgTag);
disp.appendChild(aTag);
}
axiosDum(testURL);
</script>
</body>
</html>
결과는 뻔하디 뻔하게 아래와 같당.
누차 누차 누렇게 곰팡이 필 정도로 반복 이야기 하는 거지만
현실에선 비동기가 아닌 걸 찾기가 더 힘들당. 인생은 비동기당.
그런데 비동기 개념이 어렵당?
결론은 이렇당... 당신이 너무 개인적인 건 아닐깡?
async / await 를 잘 쓰는 사람과 어서 결혼하장.
동시에 진행 되어야 할 일이 산 위에 산더미 위에 산더미당
사실 내 머리칼은 오래전 부터 하얗다.
염색으로 거짓 머리칼을 세상에 날렸다.
겉은 검지만, 살짝만 들어도 뿌리 근처는
모두 크리스마스 눈처럼 새하얗다.
나조차 머리칼이 희다는 사실을 때때로 잊는다.
큰 착각을 작은 행복으로 눈 가리고 아웅이당.
난 벌써 이미 꽤나 늙었는데, 색칠 좀 했다고
허리가 펴지고, 무릎이 스프링이 되지는 않는데
염색을 더 철저히 해야겠다.
뿌리까지 까매지도록.......
어디선가 지겹단 향기를 가득 머금은 목소리가 들린다.
그냥 마음대로 하세용~~
https://www.youtube.com/watch?v=z-xfGoabp
ag-grid 간단 사용법(사용법 업그레이드!) (8) | 2025.04.07 |
---|---|
주민번호 생성기 (0) | 2025.03.24 |
노션에 등장 블록 에디터 (editor.js) (6) | 2025.03.12 |
네이버 오늘 날씨 한번 가져와 보깅깅 (2) | 2025.03.12 |
faker-js 이용 가짜(Dummy) 데이터 마궁 맹글깅(쪼메 바뀜) (0) | 2024.10.24 |