【问题标题】:Azure block-blob storage uploading same file in succession fails连续上传相同文件的 Azure 块 Blob 存储失败
【发布时间】:2015-07-13 05:56:39
【问题描述】:

我正在使用 Azure 块 Blob 存储来保存我的文件。这是我上传文件的代码。

我在同一个请求中为同一个文件调用了两次如下的方法; 该方法的第一次调用按预期保存文件,但第二次调用将文件保存为长度为 0,因此我无法显示图像并且不会发生错误。

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        UploadFile(file);
        UploadFile(file); 
        return View();
    }

      public static string UploadFile(HttpPostedFileBase file){

        var credentials = new StorageCredentials("accountName", "key");

        var storageAccount = new CloudStorageAccount(credentials, true);

        var blobClient = storageAccount.CreateCloudBlobClient();

        var container = blobClient.GetContainerReference("images");

        container.CreateIfNotExists();

        var containerPermissions = new BlobContainerPermissions
        {
            PublicAccess = BlobContainerPublicAccessType.Blob
        };

        container.SetPermissions(containerPermissions);

        var blockBlob = container.GetBlockBlobReference(Guid.NewGuid().ToString());

        blockBlob.Properties.ContentType = file.ContentType;

        var azureFileUrl = string.Format("{0}", blockBlob.Uri.AbsoluteUri);

        try
        {
            blockBlob.UploadFromStream(file.InputStream);
        }

        catch (StorageException ex)
        {
            throw;
        }
        return azureFileUrl ;
    }

我只是发现下面的解决方案和我的一样奇怪,但它没有帮助。

Strange Sudden Error "The number of bytes to be written is greater than the specified ContentLength"

有什么想法吗? 谢谢

【问题讨论】:

  • 顺便说一句,你为什么要调用这个方法两次?

标签: azure azure-storage azure-blob-storage


【解决方案1】:

您需要将流的位置重新设置回开头。将此行放在 UploadFile 方法的顶部。

file.InputStream.Seek(0, SeekOrigin.Begin);

【讨论】:

  • 感谢您的回复,这解决了我的问题。实际上我要重构这个方法来保存不同大小的图像,我需要在同一个帖子操作中保存同一个文件的 2 个版本,所以无论如何我会用不同的宽度和高度参数调用它两次。关于 seek 方法的逻辑是什么?我正在调用该方法,因此我实例化了块 blob 的不同实例等。为什么我需要再次从 0 开始?
  • 是的,但是源文件(发布的文件)的文件指针在将其流式传输到第一个 blob 后位于文件的末尾。因此,如果您要再次阅读,则必须将其移回开头。
猜你喜欢
  • 1970-01-01
  • 2018-09-02
  • 2015-06-16
  • 2016-05-11
  • 1970-01-01
  • 2016-04-27
  • 2021-01-09
  • 2017-01-24
  • 2017-08-19
相关资源
最近更新 更多