Using Azure Blobs with Azure Website

2020-07-23 05:10发布

问题:

I'm in the process of making an MVC Windows Azure website which involves users uploading images. I wanted to store the images in blobs. I searched for tutorials but most of them deal with Webapps rather than MVC websites.

The only useful tutorial I found was: http://www.codeproject.com/Articles/490178/How-to-Use-Azure-Blob-Storage-with-Azure-Web-Sites

I'm new to the whole MVC/Windows Azure/Visual Studio scene and I got confused at Step 7 where I had to connect to Cloud Storage Account.

var storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);

I can't figure out where I'm supposed to put that bit of a code.

Same for the code in Step 8: Creating a container

blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
    // configure container for public access
    var permissions = container.GetPermissions();
    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
    container.SetPermissions(permissions);
}

And Step 9: Save the Image to a BLOB

string uniqueBlobName = string.Format("productimages/image_{0}{1}", 
   Guid.NewGuid().ToString(), Path.GetExtension(image.FileName));
CloudBlockBlob blob = blobStorage.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = image.ContentType;
blob.UploadFromStream(image.InputStream);

Any help will be really appreciated. Any other links to relevant tutorials are also welcome.

Thanks a lot!

回答1:

I assume you've added the Windows Azure Storage NuGet package to your Web App project? That didn't seem explicit in the reference you quoted, but if you hadn't you'd be seeing a bunch of unresolved compiler errors.

In terms of where the code goes, it's rather up to you. The assignment to storageAccount is like setting a database connection string; nothing is going across the wire, so you could set it once perhaps and make it available throughout your application as part of some static class instance.

In terms of creating a container, you'd do this whenever you want to store data - consider it tantamount to creating a folder in a file system or maybe a table in a relational database. If your application is always storing information in the same "hard-coded" container, you could set your container up ahead of time in the portal and not create in code.

Putting code like this in though provides a bit of resiliency in case the container got deleted through some external process; the same way that an app using SQL Server could check for the existence of an Employee table before doing updates/retrieves, since it's possible (but not likely) someone deleted the Employee table via some other SQL tool.

Saving the image to the blob would be put directly behind whatever controller is responsible for initiating that action. This is where you're doing the 'real' work. The code in your sample specifically references a container productimages, so it could be immediately preceded by the code in Step 8 if you wanted to be certain that there no chance the container was deleted (through the portal, for instance). Again, that would be similar to checking for the existence of a database table in traditional client/server code everytime you accessed data in it (which most of us might consider overkill and we'd resort to exception handling to cover that contingency).



回答2:

Old question but still may help noobs!

Azure Webapps do accept MVC apps. Webapps on Azure are just a container which Im sure can take different types of ASP.NET based applications, Forms or MVC, C# or VB.net.

Assuming you know the basics of an MVC application you can just create the Azure Webapp and publish it to there. It's as straight forward as that.

This code:

var storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);

And this:

blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
    // configure container for public access
    var permissions = container.GetPermissions();
    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
    container.SetPermissions(permissions);
}

Can go in a new class specifically for Blob services e.g. call it something like blobServices.cs and save it in the root of your MVC app and it can look like so:

    var storageAccount = CloudStorageAccount.Parse(
            ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);

    blobStorage = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
    if (container.CreateIfNotExist())
    {
        // configure container for public access
        var permissions = container.GetPermissions();
        permissions.PublicAccess = BlobContainerPublicAccessType.Container;
        container.SetPermissions(permissions);
    }

Which is probably the best practice. From there on in the Controller/s of your MVC app you can do something like this:

namespace blabla.cs
{

   public controller myBlobController
    {

      //instantiate the blob service
      BlobProfileImageServices _blobServices = new BlobProfileImageServices();

       public public ActionResult Index()
        {



            //call your blob storage service
            //and loop through each blob
            CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
            List<string> blobs = new List<string>();
            foreach (var blobItem in blobContainer.ListBlobs())
            {
                blobs.Add(blobItem.Uri.ToString());

            }


      }

    }
}