我的上传工作方式如下:
以下是一些背景信息:
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();
}
任何人都知道我犯了哪个错误,我觉得我可能需要将uploadToBlob分开,因为它会导致流错误。任何帮助,将不胜感激。以下是一些供参考的图片:
答案 0 :(得分:2)
正如Camilo Terevinto所说,你需要在调用ResizeImage()之后设置stream.Position = 0;
。那么它应该适合你。
var resizedStream = ResizeImage(stream);
stream.Position = 0 //add this code.
var uploadedFileUrl = await UploadFileAsBlob(stream, name);