Last active
August 29, 2015 14:11
-
-
Save jakobt/a3760c5309a7befde9cd to your computer and use it in GitHub Desktop.
"Restream" images to Azure Blob Storage from Web API
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
| public class AutoGeneratingImageNameAzureBlobStorageMultipartProvider : MultipartStreamProvider | |
| { | |
| /* Let the consumer read the generated filenames and the headers after uploading for persisting to database etc. */ | |
| public Dictionary<string, HttpHeaders> UploadedFiles { get; set; } | |
| private readonly bool _returnFullUri; | |
| private readonly string _blockprefix; | |
| private readonly CloudBlobContainer _container; | |
| protected Dictionary<string,string> ImageMediaTypesToExtensions = new Dictionary<string, string>() | |
| { | |
| {"image/gif", ".gif"}, | |
| {"image/jpeg", ".jpg"}, | |
| {"image/png", ".png"} | |
| }; | |
| public AutoGeneratingImageNameAzureBlobStorageMultipartProvider(CloudBlobContainer container, string blockprefix = "", bool returnFullUri = true) | |
| { | |
| _blockprefix = blockprefix; | |
| _container = container; | |
| _returnFullUri = returnFullUri; | |
| UploadedFiles = new Dictionary<string, HttpHeaders>(); | |
| } | |
| /* According to documentation the caller is responsible for closing the returned stream */ | |
| public override Stream GetStream(HttpContent parent, HttpContentHeaders headers) | |
| { | |
| string mediatype = headers.ContentType.MediaType.ToLower(); | |
| string extension; | |
| if (!ImageMediaTypesToExtensions.TryGetValue(mediatype, out extension)) | |
| { | |
| throw new FormatException(string.Format("Unknown image mediatype: '{0}' for file with original name '{1}'", mediatype, headers.ContentDisposition.FileName)); | |
| } | |
| string filename = string.Concat(Guid.NewGuid().ToString(), extension); | |
| CloudBlockBlob blob = _container.GetBlockBlobReference(string.Concat(_blockprefix, filename)); | |
| UploadedFiles.Add(_returnFullUri ? blob.Uri.AbsoluteUri : filename, headers); | |
| return blob.OpenWrite(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment