Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Azure Blob Container Web API Image Upload
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
namespace MyWeb.Extensions
{
public class BlobStorageMultipartStreamProvider : MultipartStreamProvider
{
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
Stream stream = null;
ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
if (contentDisposition != null)
{
if (!String.IsNullOrWhiteSpace(contentDisposition.FileName))
{
string connectionString = ConfigurationManager.AppSettings["my-connection-string"];
string containerName = ConfigurationManager.AppSettings["my-container"];
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
CloudBlockBlob blob = blobContainer.GetBlockBlobReference(contentDisposition.FileName);
stream = blob.OpenWrite();
}
}
return stream;
}
}
}
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using MyWeb.Extensions
namespace MyWeb.Controllers
{
public class ImageUploadController : ApiController
{
public async Task<HttpResponseMessage> PostFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
try
{
MultipartStreamProvider provider = new BlobStorageMultipartStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
}
catch (Exception)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.