Skip to content

Instantly share code, notes, and snippets.

@JamesRandall
Last active March 19, 2020 23:12
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JamesRandall/11088079 to your computer and use it in GitHub Desktop.
Save JamesRandall/11088079 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