使用Web Api将文件上载到Azure blob

时间:2017-02-21 07:15:58

标签: c# angularjs asp.net-web-api azure-blob-storage

我需要将文件上传到Azure blob。我已尝试如下所示。但它不起作用。希望我做错了。早些时候我使用文件系统存储图像。但是现在我需要将它存储在Blob中。

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

Web Api方法

[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方法

           //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);
                    }
                }
            };

堆栈跟踪

  

在   Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync [T](RESTCommand 1 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, Nullable 1长度,AccessCondition accessCondition,   BlobRequestOptions选项,OperationContext operationContext)中   c:\ Program Files   (86)\詹金斯\工作空间\ release_dotnet_master \ LIB \ ClassLibraryCommon \斑点\ CloudBlockBlob.cs:线   397在   Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStream(流   source,AccessCondition accessCondition,BlobRequestOptions选项,   C:\ Program Files中的OperationContext operationContext)   (86)\詹金斯\工作空间\ release_dotnet_master \ LIB \ ClassLibraryCommon \斑点\ CloudBlockBlob.cs:线   295在   Joshi.IP.WebApi.Controllers.PictureController.d__0.MoveNext()   在D:\ my \ my.WebApi \ WebApi \ Controllers \ PictureController.cs:line   116

异常消息:

  

远程服务器返回错误:(404)Not Found。

Blob容器

enter image description here

1 个答案:

答案 0 :(得分:1)

您的存储帐户名为ippictures,但容器名为ip-pictures。在您的代码中,您执行blobClient.GetContainerReference("ippictures");而不是blobClient.GetContainerReference("ip-pictures");

您可以通过检查指定的容器是否存在来为这种情况添加安全网:

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