Custom Storage Provider

Custom Storage Provider

Implement a custom storage provider to save uploaded files to any backend: Azure Blob, AWS S3, MongoDB GridFS, or your own storage. Implement the IUploaderProvider interface and register it in web.config appSettings.

Drag & drop files here, or paste from clipboard
<%-- 1. Implement the IUploaderProvider interface --%>
public class AzureBlobProvider : IUploaderProvider
{
    private readonly CloudBlobContainer _container;

    public AzureBlobProvider()
    {
        string connStr = ConfigurationManager
            .AppSettings["AzureStorageConnection"];
        var account = CloudStorageAccount.Parse(connStr);
        var client = account.CreateCloudBlobClient();
        _container = client.GetContainerReference("uploads");
        _container.CreateIfNotExists();
    }

    public UploadResult Save(
        Stream stream, string fileName, string contentType)
    {
        string blobName = Guid.NewGuid() + "/" + fileName;
        var blob = _container.GetBlockBlobReference(blobName);
        blob.Properties.ContentType = contentType;
        blob.UploadFromStream(stream);
        return new UploadResult
        {
            FileId = blobName,
            FileName = fileName,
            Url = blob.Uri.ToString()
        };
    }

    public FileResult GetFile(string fileId)
    {
        var blob = _container.GetBlockBlobReference(fileId);
        var ms = new MemoryStream();
        blob.DownloadToStream(ms);
        ms.Position = 0;
        return new FileResult
        {
            Stream = ms,
            ContentType = blob.Properties.ContentType
        };
    }

    public void Delete(string fileId)
    {
        _container.GetBlockBlobReference(fileId)
            .DeleteIfExists();
    }
}

<%-- 2. Register in web.config appSettings --%>
<appSettings>
    <add key="AjaxUploader:StorageProvider"
         value="MyApp.Providers.AzureBlobProvider, MyApp" />
    <add key="AzureStorageConnection"
         value="DefaultEndpointsProtocol=https;AccountName=...;AccountKey=..." />
</appSettings>

<%-- 3. Or register in Global.asax Application_Start --%>
protected void Application_Start()
{
    AjaxUploaderConfig.StorageProvider =
        new AzureBlobProvider();
}