개발Story

프로젝트를 진행하면서 API통신을 이용해 BLOB값을 받아 파일을 다운로드 할 필요가 있었다.

보통 JQUERY AJAX통신을 이용하여 API를 진행하였다.

 

예를 들어 

<html />
$.ajax({ url:'example.php' // 요청 할 주소 async:true,// false 일 경우 동기 요청으로 변경 type:'POST' // GET, PUT data: { Name:'ajax', Age:'10' },// 전송할 데이터 dataType:'text',// xml, json, script, html beforeSend:function(jqXHR) {},// 서버 요청 전 호출 되는 함수 return false; 일 경우 요청 중단 success:function(jqXHR) {},// 요청 완료 시 error:function(jqXHR) {},// 요청 실패. complete:function(jqXHR) {}// 요청의 실패, 성공과 상관 없이 완료 될 경우 호출 }); 출처: https://webinformation.tistory.com/22 [끄적끄적]

보통 이런식으로 API통신을 이용했지만

AJAX에서 BLOB를 통신하면 BLOB 값이 2배로 부풀려져서 통신되는 ERROR가 있었다.

 

 

JQUERY 3.0이상 버전에서는 xhrFields 옵션을 통해서 blob값을 정제 할 수 있다고 하는데 프로젝트에서 사용하고 있는 버전은 1.대 버전이다...... 해결책으로는 javascript에 있는 xhr 통신을 이용하라는 답변이 많았지만, 옛날 방식의 통신을 진행하고 싶지 않았다.

 

<html />
jQuery.ajax({ url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e', cache:false, xhrFields:{ responseType: 'blob' }, success: function(data){ var img = document.getElementById('img'); var url = window.URL || window.webkitURL; img.src = url.createObjectURL(data); }, error:function(){ } });

 

그래서 찾은게 FEATCH API 통신.

 

사용법은 대충 이러하다.

<html />
function postData(url = '', data = {}) { // Default options are marked with * return fetch(url, { method: 'POST', // *GET, POST, PUT, DELETE, etc. mode: 'cors', // no-cors, cors, *same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json', // 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrer: 'no-referrer', // no-referrer, *client body: JSON.stringify(data), // body data type must match "Content-Type" header }) .then(response => response.json()); // parses JSON response into native JavaScript objects }

프라미스가 내장되어있어서 then, catch 문법 사용이 가능하다/

 

 

<html />
fetch(myRequest) .then(response => response.blob()) .then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; });

상황에 맞게 통신을 하고 response.blob() 를 하면 blob를 제대로 return 받을 수 있다.

 

뭐 blob로 파일을 다운로드 받는 방법은 아래와 같이 a태그를 선언 후 blob파일을 url로 뜬다음 a태그를 클릭시키면 된다. 데이터가 문제인가 괜히 엉뚱한데서 고민하느라 하루정도 시간이 걸렸다. jquery 젠장...

 

이제 되도록 fetch api를 사용하여 개발을 해야겠다.

아 맞다 내가 쓴 api는 이상하게 json 형태로 값을 넘기는게 아니라 쿼리스트링 형태로 값을 넘겨줘야 응답을 했다.

<html />
var a = document.createElement("a"); var url = URL.createObjectURL(reponse) a.href = url; a.download = filename; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url);

 

profile

개발Story

@슬래기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!