1
votes

I need to upload files to Azure blob.I have tried as shown below.But it doesn't work.Hope I'm doing it wrongly.Earlier I have used the file system to store images.But now I need to store it in Blob.

Note : blockBlob.UploadFromStream(filestream);//after this point it doesn't work

Web Api Method

[HttpPost]
public async Task<HttpResponseMessage> AddPictures()
   {
       if (!Request.Content.IsMimeMultipartContent())
        {
          Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        var newImageName = string.Empty;
        var path = System.Web.Hosting.HostingEnvironment.MapPath("~");
        var provider = GetMultipartProvider();
        await Request.Content.ReadAsMultipartAsync(provider);

         foreach (var r in provider.FileData)
          {
              var uploadedFileInfo = new FileInfo(r.LocalFileName);
              var originalFileName = GetDeserializedFileName(r);
              var extension = Path.GetExtension(originalFileName);
              if (extension == null) continue;

              var ext = extension.ToLower();
              var guid = Guid.NewGuid().ToString();
              newImageName = guid + ext;

              var storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials("pictures", "key"),true);

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

              // Retrieve reference to a previously created container.
              var container = blobClient.GetContainerReference("ippictures");

              // Retrieve reference to a blob named "myblob".
              var blockBlob = container.GetBlockBlobReference(newImageName);

              using (var filestream = File.OpenRead(r.LocalFileName))
              {
                 blockBlob.UploadFromStream(filestream);//after this point it doesn't work
              }
              File.Delete(r.LocalFileName);

          }
              return Request.CreateResponse(HttpStatusCode.OK, new { newImageName });
       }

AngularJS method

           //to add Pictures
            vm.addPictures = function ($files, errFiles) {
                vm.upload = [];
                vm.errFiles = errFiles;
                if ($files && $files.length) {
                    //$files: an array of files selected, each file has name, size, and type
                    for (var i = 0; i < $files.length; i++) {
                        var $file = $files[i];
                        (function (index) {
                            vm.upload[index] = upload.upload({
                                url: "/api/Picture/AddPictures",
                                method: "POST",
                                data: {},
                                file: $file
                            }).progress(function () {
                            }).success(function (data) {
                                vm.pictureList.push({
                                    id: vm.pictureList.length + 1,
                                    url: '/common/pictures/' + data.newImageName,
                                    note: '',
                                    isSelected: true,
                                });

                            }).error(function () {
                            });
                        })(i);
                    }
                }
            };

Stack trace

at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 604 at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStreamHelper(Stream source, Nullable1 length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlockBlob.cs:line 397 at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStream(Stream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlockBlob.cs:line 295 at Joshi.IP.WebApi.Controllers.PictureController.d__0.MoveNext() in D:\my\my.WebApi\WebApi\Controllers\PictureController.cs:line 116

Exception message:

The remote server returned an error: (404) Not Found.

Blob container

enter image description here

1
What do you mean by 'it does not work'? Do you get any errors?Peter Bons
what version of MVC are you using? I'm assuming MVC 4?Svek
ASP.net MVC 5 and Web api 5 @SvekSampath
please see the stack trace @PeterBonsSampath
Can you post the message of the exception as well?Peter Bons

1 Answers

2
votes

Your storage account is called ippictures, but the container is called ip-pictures. In your code you do blobClient.GetContainerReference("ippictures"); instead of blobClient.GetContainerReference("ip-pictures");

You could add a safety net for these kind of situations by checking whether the specified container exists or not:

var container = blobClient.GetContainerReference("ip-pictures");
container.CreateIfNotExists()