sourcetip

zure에서 파일 업로드 후 BLOB-URL을 가져오는 방법

fileupload 2023. 5. 23. 22:21
반응형

zure에서 파일 업로드 후 BLOB-URL을 가져오는 방법

저는 웹과 작업자 역할을 연결하려고 합니다.그래서 저는 사용자가 동영상 파일을 업로드할 수 있는 페이지를 가지고 있습니다.파일이 커서 쿼리를 사용하여 파일을 보낼 수 없습니다.그래서 Blob Storage에 업로드하고 url을 쿼리로 보내려고 합니다.하지만 저는 이 URL을 얻는 방법을 모릅니다.

누가 나를 도와줄 수 있나요?

를 사용하여 블롭을 블롭 저장소에 업로드한다고 가정합니다.다음의 인스턴스를 생성하여 Net 스토리지 클라이언트 라이브러리CloudBlockBlob당신은 블롭의 속성을 읽음으로써 블롭의 URL을 얻을 수 있습니다.

static void BlobUrl()
{
    var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    var cloudBlobClient = account.CreateCloudBlobClient();
    var container = cloudBlobClient.GetContainerReference("container-name");
    var blob = container.GetBlockBlobReference("image.png");
    blob.UploadFromFile("File Path ....");//Upload file....

    var blobUrl = blob.Uri.AbsoluteUri;
}

Pastebin에서 예제

파이썬 사용자의 경우blob_client.url

안타깝게도 https://learn.microsoft.com 에는 문서화되어 있지 않습니다.

from azure.storage.blob import BlobServiceClient
# get your connection_string - look at docs
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client(storage_container_name)
You can call blob_client.url
blob_client = container_client.get_blob_client("myblockblob")
with open("pleasedelete.txt", "rb") as data:
    blob_client.upload_blob(data, blob_type="BlockBlob")
print(blob_client.url)

돌아올 것입니다https://pleasedeleteblob.blob.core.windows.net/pleasedelete-blobcontainer/myblockblob

업데이트된 "Azure Storage Blobs" 패키지를 사용하는 경우 아래 코드를 사용합니다.


BlobClient blobClient = containerClient.GetBlobClient("lg.jpg");

Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", containerClient.Uri);

using FileStream uploadFileStream = File.OpenRead(fileName);

if (uploadFileStream != null) 
    await blobClient.UploadAsync(uploadFileStream, true);

var absoluteUrl= blobClient.Uri.AbsoluteUri;

2020년 기준으로 완전하게 작동하는 자바스크립트 솔루션:

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

const AZURE_STORAGE_CONNECTION_STRING = '<connection string>'

async function main() {
  // Create the BlobServiceClient object which will be used to create a container client
  const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);

  // Make sure your container was created
  const containerName = 'my-container'

  // Get a reference to the container
  const containerClient = blobServiceClient.getContainerClient(containerName);
  // Create a unique name for the blob
  const blobName = 'quickstart.txt';

  // Get a block blob client
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);

  console.log('\nUploading to Azure storage as blob:\n\t', blobName);

  // Upload data to the blob
  const data = 'Hello, World!';
  await blockBlobClient.upload(data, data.length);
  
  console.log("Blob was uploaded successfully. requestId: ");
  console.log("Blob URL: ", blockBlobClient.url)
}

main().then(() => console.log('Done')).catch((ex) => console.log(ex.message));

여기 V12 길이 있습니다.변수 이름이 정확한지는 장담할 수 없지만 코드는 작동합니다.

protected BlobContainerClient AzureBlobContainer
{
  get
  {
    if (!isConfigurationLoaded) { throw new Exception("AzureCloud currently has no configuration loaded"); }
    if (_azureBlobContainer == null)
    {
      if (!string.IsNullOrEmpty(_configuration.StorageEndpointConnection))
      {

        BlobServiceClient blobClient = new BlobServiceClient(_configuration.StorageEndpointConnection);
        BlobContainerClient container = blobClient.GetBlobContainerClient(_configuration.StorageContainer);
        container.CreateIfNotExists();
        _azureBlobContainer = container;
      }
    }
    return _azureBlobContainer;
  }
}

public bool UploadFileToCloudStorage(string fileName, Stream fileStream)
{
  BlobClient cloudFile = AzureBlobContainer.GetBlobClient(fileName);
  cloudFile.DeleteIfExists();
  fileStream.Position = 0;
  cloudFile.Upload(fileStream);
  return true;
}

public BlobClient UploadFileToCloudStorageWithResults(string fileName, Stream fileStream)
{
  BlobClient cloudFile = AzureBlobContainer.GetBlobClient(fileName);
  cloudFile.DeleteIfExists();
  fileStream.Position = 0;
  cloudFile.Upload(fileStream);

  return cloudFile;
}

public Stream DownloadFileStreamFromCloudStorage(string fileName)
{
  BlobClient cloudFile = AzureBlobContainer.GetBlobClient(fileName);
  Stream fileStream = new MemoryStream();
  cloudFile.DownloadTo(fileStream);
  return fileStream;
}

안녕하세요, 제가 어떻게 답변에 같은 댓글을 다시 달았는지 몰랐습니다.이 스토리지 BLOB가 BLOB에서 URL을 얻는 과정에서 어떻게 작동하는지에 대한 자세한 설명과 함께 아래의 제 정답을 찾아주세요.

필요한 경우 여러 위치에 쉽게 연결할 수 있도록 web.config 파일에 연결 문자열을 추가합니다.

<connectionStrings>

<add name="BlobStorageConnection" connectionString="DefaultEndpointsProtocol=https;AccountName=accName;AccountKey=xxxxxxxxxxxxxxxxxx YOU WILL FIND THIS in your AZURE ACCOUNT xxxxxxxxxx==;EndpointSuffix=core.windows.net"/>

이 문자열은 web.config 파일에서 가져올 수 있습니다.

string BlobConnectionString = ConfigurationManager.ConnectionStrings["BlobStorageConnection"].ConnectionString;
     public string GetFileURL()
        {
        //This will create the storage account to get the details of account.
        CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(BlobConnectionString);

        //create client
        CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();

        //Get a container
        CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("ContainerName");

        //From here we will get the URL of file available in Blob Storage.
        var blob1 = cloudBlobContainer.GetBlockBlobReference(imageName);
        string FileURL=blob1.Uri.AbsoluteUri;
        return FileURL;

    }

이와 같이 파일(또는 이미지) 이름이 있으면 파일의 URL을 얻을 수 있습니다.

언급URL : https://stackoverflow.com/questions/16961933/how-to-get-blob-url-after-file-upload-in-azure

반응형