JavaScript 또는 TypeScript를 사용하여 Blob 업로드

이 문서에서는 JavaScript용 Azure Storage 클라이언트 라이브러리를 사용하여 Blob을 업로드하는 방법을 보여 줍니다. 파일 경로, 스트림, 버퍼 또는 텍스트 문자열에서 블록 Blob에 데이터를 업로드할 수 있습니다. 인덱스 태그를 사용하여 Blob을 업로드할 수도 있습니다.

필수 조건

  • 이 문서의 예제에서는 JavaScript용 Azure Blob Storage 클라이언트 라이브러리로 작업하도록 프로젝트가 이미 설정되어 있다고 가정합니다. 패키지 설치, 모듈 가져오기, 데이터 리소스 작업을 위한 권한 있는 클라이언트 개체 만들기 등 프로젝트를 설정하는 방법에 대한 자세한 내용은 Azure Blob Storage 및 JavaScript 시작을 참조하세요.
  • 권한 부여 메커니즘에는 업로드 작업을 수행할 수 있는 권한이 있어야 합니다. 자세한 내용은 다음 REST API 작업에 대한 권한 부여 지침을 참조하세요.

블록 Blob에 데이터 업로드

다음 메서드를 사용하여 블록 Blob에 데이터를 업로드할 수 있습니다.

이러한 각 메서드는 BlockBlobClient 개체를 사용하여 호출할 수 있습니다.

Note

Azure Storage 클라이언트 라이브러리는 동일한 Blob에 대한 동시 쓰기를 지원하지 않습니다. 앱에 동일한 Blob에 쓰는 여러 프로세스가 필요한 경우 예측 가능한 환경을 제공하기 위해 동시성 제어 전략을 구현해야 합니다. 동시성 전략에 대한 자세한 내용은 Blob Storage에서 동시성 관리를 참조하세요.

파일 경로에서 블록 Blob 업로드

다음 예제에서는 로컬 파일 경로에서 블록 Blob을 업로드합니다.

// containerClient: ContainerClient object
// blobName: string, includes file extension if provided
// localFilePath: fully qualified path and file name
async function uploadBlobFromLocalPath(containerClient, blobName, localFilePath){
  
  // Create blob client from container client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  await blockBlobClient.uploadFile(localFilePath);
}

스트림에서 블록 Blob 업로드

다음 예제는 읽기 가능한 스트림을 생성한 후 해당 스트림을 업로드하여 블록 Blob을 업로드하는 방법을 보여줍니다.

// containerClient: ContainerClient object
// blobName: string, includes file extension if provided
// readableStream: Readable stream, for example, a stream returned from fs.createReadStream()
async function uploadBlobFromReadStream(containerClient, blobName, readableStream) {
  
  // Create blob client from container client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  // Upload data to block blob using a readable stream
  await blockBlobClient.uploadStream(readableStream);
}

버퍼에서 블록 Blob 업로드

다음 예제에서는 Node.js 버퍼에서 블록 Blob을 업로드합니다.

// containerClient: ContainerClient object
// blobName: string, includes file extension if provided
// buffer: blob contents as a buffer, for example, from fs.readFile()
async function uploadBlobFromBuffer(containerClient, blobName, buffer) {

  // Create blob client from container client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  // Upload buffer
  await blockBlobClient.uploadData(buffer);
}

문자열로부터 블록 블롭 업로드

다음 예제에서는 문자열을 사용하여 블록 Blob을 업로드합니다.

// containerClient: ContainerClient object
// blobName: string, includes file extension if provided
// fileContentsAsString: blob content
async function uploadBlobFromString(containerClient, blobName, fileContentsAsString){
  
  // Create blob client from container client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  await blockBlobClient.upload(fileContentsAsString, fileContentsAsString.length);
}

구성 옵션으로 블록 blob 업로드

Blob을 업로드할 때 클라이언트 라이브러리 구성 옵션을 정의할 수 있습니다. 이러한 옵션을 조정하여 성능을 개선하고 안정성을 향상시키고 비용을 최적화할 수 있습니다. 이 섹션의 코드 예제에서는 BlockBlobParallelUploadOptions 인터페이스를 사용하여 구성 옵션을 설정하는 방법과 이러한 옵션을 업로드 메서드 호출에 매개 변수로 전달하는 방법을 보여줍니다.

업로드할 때 데이터 전송 옵션 지정

BlockBlobParallelUploadOptions에서 속성을 구성하여 데이터 전송 작업에 대한 성능을 향상시킬 수 있습니다. 다음 표에서는 구성할 수 있는 속성과 설명을 나열합니다.

속성 설명
blockSize 업로드 작업의 일부로 각 요청에 대해 전송할 최대 블록 크기.
concurrency 단일 병렬 전송의 일부로 지정된 시간에 발급되는 최대 병렬 요청 수.
maxSingleShotSize 데이터 크기가 이 값보다 작거나 같으면 청크로 나뉘지 않고 단일 배치로 업로드됩니다. 단일 실행에서 데이터를 업로드하면 블록 크기가 무시됩니다. 기본값은 256MiB입니다.

다음 코드 예제에서는 BlockBlobParallelUploadOptions에 대한 값을 설정하고 업로드 메서드 호출의 일부로 옵션을 포함하는 방법을 보여줍니다. 샘플에 제공된 값은 권장 사항이 아닙니다. 이러한 값을 올바르게 조정하려면 앱의 특정 요구 사항을 고려해야 합니다.

// containerClient: ContainerClient object
// blobName: string, includes file extension if provided
// localFilePath: fully qualified path and file name
async function uploadWithTransferOptions(containerClient, blobName, localFilePath) {
  
  // Specify data transfer options
  const uploadOptions = {
    blockSize: 4 * 1024 * 1024, // 4 MiB max block size
    concurrency: 2, // maximum number of parallel transfer workers
    maxSingleShotSize: 8 * 1024 * 1024, // 8 MiB initial transfer size
  } 

  // Create blob client from container client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  // Upload blob with transfer options
  await blockBlobClient.uploadFile(localFilePath, uploadOptions);
}

데이터 전송 옵션 튜닝에 대한 자세한 내용은 JavaScript를 사용하여 업로드 및 다운로드에 대한 성능 튜닝을 참조하세요.

업로드할 때 데이터 전송 유효성 검사 지정

CRC64를 사용한 전송 유효성 검사는 Azure Blob Storage 클라이언트 수준 데이터 무결성을 제공하므로 애플리케이션에서 보낸 데이터가 Azure 저장되고 읽은 데이터와 동일한지 확인할 수 있습니다. 사용하도록 설정하면 Blob SDK는 업로드 및 다운로드 작업 중에 CRC64 체크섬을 계산하고 유효성을 검사하며, 서비스는 수신하고 반환하는 데이터에 대해 CRC64 체크섬을 독립적으로 계산하고 유효성을 검사합니다. 각 요청 및 전체 데이터 스트림에서 유효성 검사가 수행되므로 블록 업로드 또는 범위가 지정된 읽기와 같은 파티션에서 데이터가 전송되는 경우에도 전체 Blob이 확인됩니다. 자세한 내용은 구조적 본문 형식 을 참조하세요.

BlobClientConfig를 사용하여 클라이언트 수준에서 전송 유효성 검사 옵션을 정의할 수 있습니다. 이 옵션은 BlobClient 인스턴스에서 호출된 모든 메서드에 유효성 검사 옵션을 적용합니다. 또는 BlobUploadOptions와 같은 옵션을 통해 작업 수준에서 전송 유효성 검사 옵션을 재정의할 수 있습니다.

const blobServiceClient = new BlobServiceClient(
   `https://${account}.blob.core.windows.net`,
   new DefaultAzureCredential(),
   {
     uploadContentChecksumAlgorithm: "StorageCrc64",
     downloadContentChecksumAlgorithm: "StorageCrc64",
   }
);

인덱스 태그를 포함한 블록 Blob 업로드

Blob 인덱스 태그는 키-값 태그 특성을 사용하여 스토리지 계정의 데이터를 분류합니다. 이러한 태그는 데이터를 쉽게 찾을 수 있도록 검색 가능한 다차원 인덱스로 자동으로 인덱싱되고 표시됩니다.

다음 예제에서는 BlockBlobParallelUploadOptions를 사용하여 인덱스 태그가 설정된 블록 Blob을 업로드합니다.

// containerClient: ContainerClient object
// blobName: string, includes file extension if provided
// localFilePath: fully qualified path and file name
async function uploadWithIndexTags(containerClient, blobName, localFilePath) {
  
  // Specify index tags for blob
  const uploadOptions = {
    tags: {
      'Sealed': 'false',
      'Content': 'image',
      'Date': '2022-07-18',
    }
  }

  // Create blob client from container client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  // Upload blob with index tags
  await blockBlobClient.uploadFile(localFilePath, uploadOptions);
}

업로드 시 Blob의 액세스 계층 설정

BlockBlobParallelUploadOptions 인터페이스를 사용하여 업로드 시 Blob의 액세스 계층을 설정할 수 있습니다. 다음 코드 예제에서는 Blob을 업로드할 때 액세스 계층을 설정하는 방법을 보여줍니다.

// containerClient: ContainerClient object
// blobName: string, includes file extension if provided
// localFilePath: fully qualified path and file name
async function uploadWithAccessTier(containerClient, blobName, localFilePath) {
  
  // Specify access tier
  const uploadOptions = {
    // 'Hot', 'Cool', 'Cold', or 'Archive'
    tier: 'Cool',
  }

  // Create blob client from container client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  // Upload blob to cool tier
  await blockBlobClient.uploadFile(localFilePath, uploadOptions);
}

액세스 계층은 블록 Blob에 대해서만 설정할 수 있습니다. 블록 Blob에 대한 액세스 계층을 Hot, Cool, Cold 또는 Archive로 설정할 수 있습니다. 액세스 계층을 Cold로 설정하려면 최소 클라이언트 라이브러리 버전, 12.13.0을 사용해야 합니다.

액세스 계층에 대한 자세한 내용은 액세스 계층 개요를 참조하세요.

리소스

JavaScript용 Azure Blob Storage 클라이언트 라이브러리를 사용하여 Blob을 업로드하는 방법에 대한 자세한 내용은 다음 리소스를 참조하세요.

REST API 작업

JavaScript용 Azure SDK에는 Azure REST API를 기반으로 빌드되는 라이브러리가 포함되어 있으므로 익숙한 JavaScript 패러다임을 통해 REST API 작업과 상호 작용할 수 있습니다. Blob을 업로드하기 위한 클라이언트 라이브러리 메서드는 다음 REST API 작업을 사용합니다.

코드 샘플

이 문서의 코드 샘플 보기(GitHub):

클라이언트 라이브러리 리소스

참고 항목

  • 이 문서는 JavaScript/TypeScript용 Blob Storage 개발자 가이드의 일부입니다. 자세한 내용은 JavaScript/TypeScript 앱 빌드에서 개발자 가이드 문서의 전체 목록을 참조하세요.