Skip to content

Instantly share code, notes, and snippets.

@aslamhadi
Last active August 9, 2016 01:54
Show Gist options
  • Save aslamhadi/a6e061517b86956b903a53fc157f92f7 to your computer and use it in GitHub Desktop.
Save aslamhadi/a6e061517b86956b903a53fc157f92f7 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Web;
using MyProject.Services.Interfaces;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
namespace MyProject.Services
{
public class AzureFileUploaderService: IAzureFileUploaderService
{
private readonly CloudStorageAccount _storageAccount;
public AzureFileUploaderService()
{
// Retrieve storage account from connection string.
_storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
}
public async Task<string> UploadPhotoAsync(HttpPostedFileBase photo, string prefix, string photoType)
{
if (photo == null || photo.ContentLength == 0)
{
return null;
}
string fullPath = null;
// Stopwatch timespan = Stopwatch.StartNew();
try
{
// Create the blob client and reference the container
CloudBlobClient blobClient = _storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(photoType);
if (await container.CreateIfNotExistsAsync())
{
// Enable public access on the newly created "images" container
await container.SetPermissionsAsync(
new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
}
var guid = Guid.NewGuid();
// Create a unique name for the images we are about to upload
string imageName = string.Format("{0}-{1}-{2}", prefix, guid, photo.FileName);
// Upload image to Blob Storage
CloudBlockBlob blockBlob = container.GetBlockBlobReference(imageName);
blockBlob.Properties.ContentType = photo.ContentType;
await blockBlob.UploadFromStreamAsync(photo.InputStream);
fullPath = blockBlob.Uri.ToString();
// timespan.Stop();
// log.TraceApi("Blob Service", "PhotoService.UploadPhoto", timespan.Elapsed, "imagepath={0}", fullPath);
}
catch (Exception ex)
{
//log.Error(ex, "Error upload photo blob to storage");
}
return fullPath;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment