上传到azure存储区返回一个空文件

时间:2018-02-03 00:30:47

标签: c# asp.net-core .net-core azure-storage azure-storage-blobs

我的上传工作方式如下:

  1. 我有两种方法,一种调整图像大小,另一种上传完整图像尺寸。
  2. 我的上传方法工作正常,因为我可以在我的blob中找到问题,当我尝试下载完整的图像时它返回一个0号文件,但调整后的图像效果很好。
  3. 以下是一些背景信息:

    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分开,因为它会导致流错误。任何帮助,将不胜感激。以下是一些供参考的图片:

    enter image description here enter image description here

1 个答案:

答案 0 :(得分:2)

正如Camilo Terevinto所说,你需要在调用ResizeImage()之后设置stream.Position = 0;。那么它应该适合你。

var resizedStream = ResizeImage(stream);
stream.Position = 0 //add this code.
var uploadedFileUrl = await UploadFileAsBlob(stream, name);