Created
July 20, 2016 21:50
-
-
Save benjanderson/0fbd3d0083dccb14971d9629c557eafd to your computer and use it in GitHub Desktop.
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 interface IFileUploader | |
{ | |
Task<FileInfo> GetUploadedFile(HttpContent content, string expectedExtension); | |
} | |
public class FileUploader : IFileUploader | |
{ | |
public async Task<FileInfo> GetUploadedFile(HttpContent content, string expectedExtension) | |
{ | |
if (!content.IsMimeMultipartContent()) | |
{ | |
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); | |
} | |
var root = ImportExportApplication.FindTemporaryDirectory(); | |
var provider = new MultipartFormDataStreamProvider(root); | |
await content.ReadAsMultipartAsync(provider); | |
MultipartFileData file = provider.FileData.FirstOrDefault(); | |
if (file == null) | |
{ | |
throw new FileNotFoundException(); | |
} | |
var extension = Path.GetExtension(file.Headers.ContentDisposition.FileName.Trim('/', '"')); | |
if (extension != expectedExtension) | |
{ | |
throw new InvalidOperationException(Resources.BadFileFormat); | |
} | |
return new FileInfo(Path.Combine(root, file.LocalFileName.Trim('/', '"'))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment