Last active
August 9, 2016 01:54
-
-
Save aslamhadi/a6e061517b86956b903a53fc157f92f7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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