Skip to content

Instantly share code, notes, and snippets.

@benjanderson
Created July 20, 2016 21:50
Show Gist options
  • Save benjanderson/0fbd3d0083dccb14971d9629c557eafd to your computer and use it in GitHub Desktop.
Save benjanderson/0fbd3d0083dccb14971d9629c557eafd to your computer and use it in GitHub Desktop.
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