My upload works the following way:
Here is some context:
public async Task<UserProfile> PostProfilePictureAsync(int userId, IFormFile file)
{
var stream = file.OpenReadStream();
var name = file.FileName;
var thumbName = "resized_"+file.FileName;
var resizedStream = ResizeImage(stream);
var uploadedFileUrl = await UploadFileAsBlob(stream, name);
var uploadedResizedUrl = await UploadFileAsBlob(resizedStream, thumbName);
var entity = await _context.UserProfile.FirstOrDefaultAsync(r => r.userId == userId);
entity.PictureUrl = uploadedFileUrl;
entity.ThumbnailUrl = uploadedResizedUrl;
_context.Entry(entity).State = EntityState.Modified;
_context.SaveChanges();
return Mapper.Map<UserProfile>(entity);
}
private Stream ResizeImage(Stream stream) {
MemoryStream result = new MemoryStream();
// Create a new image
var image = Image.FromStream(stream);
// Set the image size for the final size values
var resizedImage = new Bitmap(80, 80);
// Draw the image inside a new graphic container
Graphics g = Graphics.FromImage(resizedImage);
g.DrawImage(image,0,0,80,80);
// Save that new image and return the stream
result.Position = 0;
resizedImage.Save(result,System.Drawing.Imaging.ImageFormat.Jpeg);
result.Position = 0;
return result;
}
private async Task<string> UploadFileAsBlob(Stream stream, string filename)
{
CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("my_credentials", "my_key"), true);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("my_reference");
CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
await blockBlob.UploadFromStreamAsync(stream);
stream.Dispose();
return blockBlob?.Uri.ToString();
}
Anyone knows where I made a mistake, I sense I might need to separate the uploadToBlob because its causing errors with the stream. Any help would be appreciated. Here are some images for reference:
As Camilo Terevinto mentioned that you need to set stream.Position = 0;
after calling ResizeImage(). Then it should work correctly for you.
var resizedStream = ResizeImage(stream);
stream.Position = 0 //add this code.
var uploadedFileUrl = await UploadFileAsBlob(stream, name);