【问题标题】:Uploading to azure storage returning an empty file上传到 Azure 存储返回一个空文件
【发布时间】:2018-07-13 13:10:43
【问题描述】:

我的上传方式如下:

  1. 我有两种方法,一种调整图片大小,另一种上传完整图片大小。
  2. 我的上传方法工作正常,因为我可以在我的 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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 2017-01-04
    • 2017-01-24
    • 2017-08-19
    • 2017-12-15
    • 2020-09-04
    相关资源
    最近更新 更多