【发布时间】:2018-07-13 13:10:43
【问题描述】:
我的上传方式如下:
- 我有两种方法,一种调整图片大小,另一种上传完整图片大小。
- 我的上传方法工作正常,因为我可以在我的 blob 中找到它。当我尝试下载完整的图像时,它会返回大小为 0 的文件,但调整大小的图像工作正常。
这里有一些上下文:
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 分开,因为它会导致流错误。任何帮助,将不胜感激。以下是一些图片供参考:
【问题讨论】:
-
如果您在调用
ResizeImage()后尝试stream.Position = 0;会发生什么?好像流已经被消费了,所以上传是空的
标签: c# asp.net-core .net-core azure-storage azure-blob-storage