Forked from JamesRandall/BlobStorageMultipartStreamProvider.cs
Created
October 27, 2015 03:18
-
-
Save GFoley83/589df2959c007a957874 to your computer and use it in GitHub Desktop.
Azure Blob Container Web API Image Upload
This file contains hidden or 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.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; | |
} | |
} | |
} |
This file contains hidden or 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.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