Web_Miscellaneous / 기초 개념 / 1.1 Blob
1.1Blob
JavaScript에서 Binary Data를 다루기 위한 객체인 Blob과 ArrayBuffer
Blob이란?
Binary Large Object의 약자로, JavaScript에서 raw data를 binary로 표현하고 처리하기 위해 쓰는 데이터 object이다.
특징
- Immutable : 한번 생성되면 내용을 바꿀 수 없다.
- File-like Object : 파일은 아니지만 파일처럼 처리되어 다운로드나 서버에 업로드할 때 쓰인다.
- Data Sources : raw binary data나 string, 또는 data array로부터 만들어진다.
쓰임
- File Download : 브라우저에서 다운받을 수 있는 파일 생성
- Binary Data 처리 : 이미지, 영상, 오디오 등의 멀티미디어 파일을 다루는데 쓰임
- Server upload
- Displaying content : URL.createObjectURL을 통해 URL로 바꿀 수 있다.
사용법
- 간단한 생성 : new Blob으로 생성
javascriptconst data = ['Hello, World!']; const blob = new Blob(data, { type: 'text/plain' });
- 다운로드 링크 생성
javascript// string, array, raw binary data등으로 blob 생성 const text = 'Hello, World!'; const blob = new Blob([text], { type: 'text/plain' }); // blob으로 url을 만들 수 있다. const url = URL.createObjectURL(blob); // blob을 다운로드 받기 위한 링크를 만든다. const link = document.createElement('a'); link.href = url; link.download = 'sample.txt'; document.body.appendChild(link); link.click(); // (clean up) document.body.removeChild(link); URL.revokeObjectURL(url);
Blob.stream()
으로ReadableStream
으로 변환- 데이터 추출
FileReader.readAsArrayBuffer
로 읽을 수 있음
javascriptconst reader = new FileReader(); reader.addEventListener('loadend', () => { // reader.result contains the contents of blob as a typed array }); reader.readAsArrayBuffer(blob);
Response
로 읽을 수 있음
javascriptconst text = await new Response(blob).text();
Blob.text()
로도 읽을 수 있음
javascriptconst text = await blob.text();
File object와 ArrayBuffer
File
Blob
의 subclass로, file-like object를 blob 기능을 유지한 상태로 추가적인 metadata(filename, last modified data 등)도 가질 수 있음<input>
element를 통해 유저에게 받은 파일 등을 처리하는데 주로 쓰임
ArrayBuffer
- low-level binary data 구조
- raw memory의 fixed-length block
- File-like인 Blob과 File과 달리, binary data의 세부 정보를 미세 조정하기 위해 쓰임
- 주로 typed array로 접근(Uint8Array, Int32Array 등)
- binary data에 직접 접근해서 변경 가능
- network stream으로 데이터를 읽거나 multimedia를 decode하는데 쓰임
Blob
으로 변환 가능하고,Blob
도ArrayBuffer
로 변환 가능
References
PreviousNo previous post