2
votes

I am trying to achieve the following using azures blob storage.

  1. Upload a file to azure blob storage.
  2. Then send a http response containing a base64 string of the file.

The strange part is that I can get only one to work as it causes the other to stop working depending on the order of my code.

        HttpPostedFile image = Request.Files["froalaImage"];
        if (image != null)
        {
            string fileName = RandomString() + System.IO.Path.GetExtension(image.FileName);
            string companyID = Request.Form["companyID"].ToLower();

            // Retrieve storage account from connection string.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("StorageConnectionString"));

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(companyID);

            // Create the container if it doesn't already exist.
            container.CreateIfNotExists();

            // Retrieve reference to a blob named "filename".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

            // Create or overwrite the blob with contents from a local file.
            using (image.InputStream)
            {
                blockBlob.UploadFromStream(image.InputStream);
                byte[] fileData = null;
                using (var binaryReader = new BinaryReader(image.InputStream))
                {
                    fileData = binaryReader.ReadBytes(image.ContentLength);
                }
                string base64ImageRepresentation = Convert.ToBase64String(fileData);                   

                // Clear and send the response back to the browser.
                string json = "";
                Hashtable resp = new Hashtable();
                resp.Add("link", "data:image/" + System.IO.Path.GetExtension(image.FileName).Replace(@".", "") + ";base64," + base64ImageRepresentation);
                resp.Add("imgID", "BLOB/" + fileName);
                json = JsonConvert.SerializeObject(resp);
                Response.Clear();
                Response.ContentType = "application/json; charset=utf-8";
                Response.Write(json);
                Response.End();
            }
        }

The above code will upload the file to azure's blob storage however the base64 string will be empty.

But if I put the line blockBlob.UploadFromStream(image.InputStream); below the line string base64ImageRepresentation = Convert.ToBase64String(fileData);

I will get the base64 string no problem however the file is not uploaded correctly to azure's blob storage.

1

1 Answers

5
votes

Maybe you need to reset your stream position after the first usage?

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