I'm playing with Azure Blob Storage and I'm wondering if I can optimize this code a bit.
As you can see I'm creating folder and then uploading content to that folder before sending to Azure Storage and upon competition I'm deleting that folder it seems a bit redundant to be fair.
Now, I'm wondering if I can skip this few steps and just upload stream to azure without copying first to root folder?
Here is the code:
public async Task UploadBlobFile(IFormFile file, BlobMetadata metadata, string containerName)
{
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
BlobHttpHeaders headers = new BlobHttpHeaders
{
ContentType = "application/pdf",
ContentLanguage = "hr-HR",
};
if (file.Length > 0)
{
try
{
var rootFolder = Path.Combine(_hostingEnvironment.WebRootPath, "upload");
if (!Directory.Exists(rootFolder))
{
Directory.CreateDirectory(rootFolder);
}
// create folder if doesnt exists
var filePath = Path.Combine(rootFolder, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
// set cursor to the beginning of the stream.
stream.Position = 0;
var metadataProperties = new Dictionary<string, string>
{
{ MetadataValues.Id, metadata.Id },
{ MetadataValues.Name, metadata.Name },
{ MetadataValues.UniqueName, metadata.UniqueName }
};
var blobClient = containerClient.GetBlobClient(file.FileName);
await blobClient.UploadAsync(stream, headers, metadataProperties);
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
catch (Exception ex)
{
throw ex;
}
}
}
As fellow Bradley Uffner and pinkfloydx33 pointed out, code above can be optimized like this
public async Task UploadBlobFile(IFormFile file, BlobMetadata metadata, string containerName)
{
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
BlobHttpHeaders headers = new BlobHttpHeaders
{
ContentType = "application/pdf",
ContentLanguage = "hr-HR",
};
if (file.Length > 0)
{
using (var stream = file.OpenReadStream())
{
// set cursor to the beginning of the stream.
stream.Position = 0;
var metadataProperties = new Dictionary<string, string>
{
{ MetadataValues.Id, metadata.Id },
{ MetadataValues.Name, metadata.Name },
{ MetadataValues.UniqueName, metadata.UniqueName }
};
var blobClient = containerClient.GetBlobClient(file.FileName);
await blobClient.UploadAsync(stream, headers, metadataProperties);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.