Yuvaraj V
Yuvaraj V

Reputation: 1212

Can't set content type from using uploadFile method in @azure/storage-blob (SDK/NPM)

Can't set azure content type from node using below code. It's always storing content type as octane stream.

const { BlobServiceClient } = require('@azure/storage-blob');

const { AZURE_STORAGE_CONNECTION_STRING } = process.env;

let blobServiceClient;

async function getBlobServiceClient() {
  if (!blobServiceClient) {
    blobServiceClient = await BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
  }

  return blobServiceClient;
}

async function uploadFile(filePath, containerName) {
  const bsClient = await getBlobServiceClient();
  const containerClient = bsClient.getContainerClient(containerName);
  const blockBlobClient = containerClient.getBlockBlobClient('myImag6.png', { blobHTTPHeaders: { blobContentType: 'image/png' } });

  try {
    const res = await blockBlobClient.uploadFile(filePath);
    console.log(res);
  } catch (error) {
    console.log(error);
  }
}

The following issue seems related to this but I am not sure. https://github.com/Azure/azure-sdk-for-js/issues/6192

Please give me more info on this and how to solve this issue.

Upvotes: 0

Views: 983

Answers (2)

Bhushan
Bhushan

Reputation: 682

Did you try setting the blobHttpHeaders and passed to the uploadFile method?

const blobOptions = { blobHTTPHeaders: { blobContentType: 'image/png' } };
const res = await blockBlobClient.uploadFile(filePath, blobOptions);

Upvotes: 3

George Chen
George Chen

Reputation: 14334

Suppose it's because you don't set the BlockBlobUploadOptions in the uploadFile method, you only use it in the getBlockBlobClient method, in my below code test, it could set the content type.

    const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");

    // Enter your storage account name and shared key
    const account = "account name";
    const accountKey = "account key";

    const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
    const blobServiceClient = new BlobServiceClient(
      `https://${account}.blob.core.windows.net`,
      sharedKeyCredential
    );

    const containerName = "test";

    async function main() {
  const containerClient = blobServiceClient.getContainerClient(containerName);


  const blockBlobClient = containerClient.getBlockBlobClient('test.txt');
  const blobOptions = { blobHTTPHeaders: { blobContentType: 'text/plain' } };
  const uploadBlobResponse = await blockBlobClient.uploadFile('E:\\project\\jsstorage\\test.txt',blobOptions);

  console.log(`Upload block blob test.txt successfully`, uploadBlobResponse.requestId);
}

main();

enter image description here

Upvotes: 4

Related Questions