我实现了POST Rest服务以将文件上传到我的服务器。我现在的问题是我想按类型限制上传的文件。比方说,我只想允许上传.pdf文件。
我试图做的是
Task<Stream> task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
FileStream requestStream = (FileStream)task.Result;
但遗憾的是,无法将Stream强制转换为FileStream并通过requestStream.Name访问该类型。
是否有一种简单的方法(除了将流写入磁盘并检查类型)以获取文件类型?
答案 0 :(得分:8)
如果您将文件上传到Web API并且想要访问文件数据(Content-Disposition
),则应将该文件作为MIME多部分(multipart/form-data
)上传。
Here我展示了一些关于如何从HTML表单,Javascript和.NET上传的例子。
然后你可以这样做,这个例子只检查pdf / doc文件:
public async Task<HttpResponseMessage> Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable,
"This request is not properly formatted - not multipart."));
}
var provider = new RestrictiveMultipartMemoryStreamProvider();
//READ CONTENTS OF REQUEST TO MEMORY WITHOUT FLUSHING TO DISK
await Request.Content.ReadAsMultipartAsync(provider);
foreach (HttpContent ctnt in provider.Contents)
{
//now read individual part into STREAM
var stream = await ctnt.ReadAsStreamAsync();
if (stream.Length != 0)
{
using (var ms = new MemoryStream())
{
//do something with the file memorystream
}
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
}
public class RestrictiveMultipartMemoryStreamProvider : MultipartMemoryStreamProvider
{
public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
{
var extensions = new[] {"pdf", "doc"};
var filename = headers.ContentDisposition.FileName.Replace("\"", string.Empty);
if (filename.IndexOf('.') < 0)
return Stream.Null;
var extension = filename.Split('.').Last();
return extensions.Any(i => i.Equals(extension, StringComparison.InvariantCultureIgnoreCase))
? base.GetStream(parent, headers)
: Stream.Null;
}
}