3. JavaScript활용 - (2) Ajax : blob 파일 다운로드

한승록·2023년 12월 10일
0
post-thumbnail

1) 개념

BlobBinary Large Object의 약자로 이진 데이터를 나타내는 데 사용되는 파일 형태입니다.
주로 이미지, 오디오, 비디오, 문서 등과 같은 다양한 형식의 이진 데이터를 나타내게 됩니다.




2) 활용

이를 이전에 설명드린 fetch.then.then.catch 형태에서 첫번째 .then 에서 통신이 성공했을 때 blob 파일 형태로 넘기게 됩니다.
웹 애플리케이션에서는 Ajax요청이나 formData객체를 활용하여 전송하게 됩니다.

2-1) XMLHttpRequest

// XMLHttpRequest 객체 생성
var xhr = new XMLHttpRequest();

// 서버로의 요청 설정
xhr.open('GET', '요청을 전송할 url', true);
xhr.responseType = 'blob';

// 요청 완료 후의 콜백 함수 설정
xhr.onload = function () {
    if (xhr.status === 200) {
        // Blob 데이터 다운로드
        var blobData = xhr.response;
        
        // 여기에서 blobData를 사용하여 필요한 작업을 수행
    }
};

// 요청 전송
xhr.send();



2-2) Fetch API

// Fetch API를 사용하여 Blob 다운로드
fetch('요청을 전송할 url')
    .then(response => response.blob())
    .then(blobData => {
        // 여기에서 blobData를 사용하여 필요한 작업을 수행
    })
    .catch(error => console.error('Error fetching blob:', error));



2-3) FormData 형태로 Fetch API를 통하여 활용

// FormData 객체 생성
var formData = new FormData();

// Blob 데이터를 FormData에 추가
formData.append('file', blobData, 'filename.txt');

// Fetch API를 사용하여 서버로 업로드
fetch('요청을 전송할 url', {
    method: 'POST',
    body: formData
})
    .then(response => {
  		
  		return response.blob();
	})
    .then(blob => {
        // 서버의 응답을 처리
    })
    .catch(error => console.error('Error uploading blob:', error));
profile
개발 학습

0개의 댓글