Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ismaelgasparin/f37f729839153e6e10cbcf20582dd3c2 to your computer and use it in GitHub Desktop.
Save ismaelgasparin/f37f729839153e6e10cbcf20582dd3c2 to your computer and use it in GitHub Desktop.
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