Skip to content

Instantly share code, notes, and snippets.

@siewers
Created February 24, 2017 14:26
Show Gist options
  • Save siewers/84dc1b4fd644383d190c3478d82bcdec to your computer and use it in GitHub Desktop.
Save siewers/84dc1b4fd644383d190c3478d82bcdec to your computer and use it in GitHub Desktop.
Stream HTTP content directly to Azure blob storage
namespace Azure
{
using System.Net.Http.Headers;
public class AzureBlobContentDisposition
{
public AzureBlobContentDisposition(ContentDispositionHeaderValue headerValue)
{
this.FileName = headerValue?.FileName;
}
public string FileName { get; }
public static implicit operator string(AzureBlobContentDisposition disposition)
{
return disposition.ToString();
}
public static AzureBlobContentDisposition Parse(string disposition)
{
ContentDispositionHeaderValue headerValue;
ContentDispositionHeaderValue.TryParse(disposition, out headerValue);
return new AzureBlobContentDisposition(headerValue);
}
public override string ToString()
{
if (!string.IsNullOrWhiteSpace(this.FileName))
{
return new ContentDispositionHeaderValue("attachment")
{
FileName = this.FileName
}.ToString();
}
return string.Empty;
}
}
}
namespace Azure
{
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
public class AzureTemporaryStorage
{
private readonly CloudBlobContainer container;
public AzureTemporaryStorage(CloudBlobContainer container)
{
this.container = container;
}
public async Task<Guid> UploadAsync(HttpContent content, CancellationToken cancellationToken = default(CancellationToken))
{
content.EnsureIsMimeMultipartContent();
var blobId = Guid.NewGuid();
var writeStream = this.GetWriteStream(assetId);
var provider = new DelegateMultipartStreamProvider(writeStream);
await content.ReadAsMultipartAsync(provider, cancellationToken).ConfigureAwait(false);
return blobId;
}
private Func<HttpContent, HttpContentHeaders, Stream> GetWriteStream(Guid blobId)
{
return (content, headers) =>
{
var block = this.container.GetBlockBlobReference(blobId.ToString("N"));
block.Properties.ContentDisposition = new AzureBlobContentDisposition(headers.ContentDisposition);
block.Properties.ContentType = headers.ContentType.MediaType;
return block.OpenWrite();
};
}
}
}
namespace Azure
{
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
public class DelegateMultipartStreamProvider : MultipartStreamProvider
{
private readonly Func<HttpContent, HttpContentHeaders, Stream> getWriteStream;
public DelegateMultipartStreamProvider(Func<HttpContent, HttpContentHeaders, Stream> getWriteStream)
{
this.getWriteStream = getWriteStream;
}
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
return this.getWriteStream(parent, headers);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment