Search code examples
azureazure-storageazure-blob-storage

Azure block-blob storage uploading same file in succession fails


I' m using Azure Block Blob Storage to keep my files. Here is my code to upload file.

I m calling the method twice as below for the same file in the same request; The first call of the method saves the file as expected but the second call saves file as length of 0 so i cant display the image and no error occurs.

    [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 ;
    }

I just find the below solution which is strange like mine, but it does not help.

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

Any idea? Thanks


Solution

  • You need to reset the position of the stream back to the beginning. Put this line at the top of your UploadFile method.

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