Reputation: 399
I am trying to save an image in azure blob storage. I set the content type by code, as follows but it is readying but not uploading. What should I do?
File upload code :
[HttpPost("ListFiles")]
public async Task<List<string>> InsertFile(List<IFormFile> asset)
{
try
{
var urlList = new List<string>();
foreach (var op in asset)
{
if (CloudStorageAccount.TryParse(_config.Value.StorageConnection, out CloudStorageAccount storageAccount))
{
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(_config.Value.Container);
var postedFileExtension = Path.GetExtension(op.FileName);
var img = $@"{Guid.NewGuid()}" + postedFileExtension;
CloudBlockBlob blockBlob = container.GetBlockBlobReference(img);
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(img);
cloudBlockBlob.Properties.ContentType = op.ContentType;
await blockBlob.UploadFromStreamAsync(op.OpenReadStream());
var blob = container.GetBlockBlobReference(img);
urlList.Add(blob.Uri.AbsoluteUri);
}
}
return urlList;
}
catch (Exception e)
{
throw e;
}
}
Upvotes: 0
Views: 377
Reputation: 14324
To set content type while uploading the blob, just set the ContentType
property before calling the upload method. The below is my test code, you could have a try.
static void Main(string[] args)
{
String strorageconn = "storage string";
CloudStorageAccount storageacc = CloudStorageAccount.Parse(strorageconn);
//Create Reference to Azure Blob
CloudBlobClient blobClient = storageacc.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("test");
CloudBlockBlob blockBlob = container.GetBlockBlobReference("test.jpg");
blockBlob.Properties.ContentType = "image/jpg";
using (var filestream = System.IO.File.OpenRead(@"D:\Picture\test.jpg"))
{
blockBlob.UploadFromStream(filestream);
}
}
And use Storage Explorer to read the properties, below is the result.
Upvotes: 2
Reputation: 19407
You are currently using
var postedFileExtension = Path.GetExtension(op.FileName);
var img = $@"{Guid.NewGuid()}" + postedFileExtension;
CloudBlockBlob blockBlob = container.GetBlockBlobReference(img);
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(img);
cloudBlockBlob.Properties.ContentType = op.ContentType;
await blockBlob.UploadFromStreamAsync(op.OpenReadStream());
var blob = container.GetBlockBlobReference(img);
You are setting the ContentType
property of a variable but not committing this change to Azure. Update the code to:
var postedFileExtension = Path.GetExtension(op.FileName);
var img = $@"{Guid.NewGuid()}" + postedFileExtension;
CloudBlockBlob blockBlob = container.GetBlockBlobReference(img);
blockBlob.Properties.ContentType = op.ContentType;
await blockBlob.UploadFromStreamAsync(op.OpenReadStream());
var blob = container.GetBlockBlobReference(img);
Console.WriteLine(blob.Properties.ContentType); // Output the contentType
Upvotes: 1