JavaScript

URL 클래스, URL.createObjectURL()

폴리프레임 2025. 2. 9. 18:54
반응형

Methods

1. URL.createObjectURL(blob)

브라우저 환경에서 Blob 객체나 File 객체를 나타내는 임시 URL을 생성하는 데 사용됩니다. 이를 통해 바이너리 데이터를 직접 표시하거나 다운로드할 수 있는 URL을 만들 수 있습니다. 이 URL은 메모리에 존재하며, 브라우저를 닫거나 명시적으로 해제하지 않는 한 유효합니다.

const inputElement = document.querySelector('input[type="file"]');

inputElement.addEventListener('change', (event) => {
  const file = (event.target as HTMLInputElement).files?.[0];
  if (file) {
    const objectURL = URL.createObjectURL(file);
    console.log(objectURL); // 생성된 URL 출력
    
    // 예: 이미지를 미리보기로 표시
    const img = document.createElement('img');
    img.src = objectURL;
    document.body.appendChild(img);
  }
});

 

2. URL.revokeObjectURL(url): 생성된 임시 URL을 해제하여 메모리를 반환합니다.

URL.revokeObjectURL(objectURL);

 

3. toString(): URL의 문자열 표현을 반환합니다.

console.log(url.toString()); // 'https://example.com/path?name=JohnDoe&age=25#section2'

 

4. toJSON(): URL의 JSON 표현을 반환합니다.

console.log(url.toJSON()); // 'https://example.com/path?name=JohnDoe&age=25#section2'
// url.href 와 동일

Properties

1. href: 전체 URL 문자열을 반환하거나 설정합니다.

const url = new URL('https://example.com/path?name=JohnDoe&age=25#section2');
console.log(url.href); // 'https://example.com/path?name=JohnDoe&age=25#section2'

 

2. protocol: URL의 프로토콜을 반환하거나 설정합니다 (예: http:, https:)

console.log(url.protocol); // 'https:'

 

3. host: URL의 호스트(포트 번호 포함)를 반환하거나 설정합니다.

console.log(url.host); // 'example.com'

 

4. hostname: 포트를 제외한 호스트 이름을 반환하거나 설정합니다.

console.log(url.hostname); // 'example.com'

 

5. port: URL의 포트 번호를 반환하거나 설정합니다.

console.log(url.port); // ''

 

6. pathname: URL의 경로를 반환하거나 설정합니다.

console.log(url.pathname); // '/path'

 

7. search: URL의 쿼리 문자열을 반환하거나 설정합니다 (시작 ? 포함).

console.log(url.search); // '?name=JohnDoe&age=25'

 

8. hash: URL의 해시(# 뒤에 오는 부분)를 반환하거나 설정합니다. 

console.log(url.hash); // '#section2' 
// #section2 부분을 나타내며, 페이지 내 특정 위치를 지정합니다.