从Htt的prequestMessage内容文件名 [英] File Name from HttpRequestMessage Content
问题描述
我实现了一个POST REST服务将文件上传到我的服务器。我现在的问题是,我想通过它的类型来限制上传的文件。可以说,例如,我只想让.pdf文件上传。
I implemented a POST Rest service to upload files to my server. the problem i have right now is that i want to restrict the uploaded files by its type. lets say for example i only want to allow .pdf files to be uploaded.
我试图做的是
Task<Stream> task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
FileStream requestStream = (FileStream)task.Result;
,但不幸的是其不能将流转换为一个FileStream并经由requestStream.Name访问类型
but unfortunately its not possible to cast the Stream to a FileStream and access the type via requestStream.Name.
有没有一种简单的方法(除了流写入到磁盘,然后检查的类型)来获取文件类型?
is there an easy way (except writing the stream to the disk and check then the type) to get the filetype?
推荐答案
如果您上传文件的Web API和你想获得访问文件数据(内容处置
),你应该上传文件MIME多(的multipart / form-data的
)。
If you upload file to Web API and you want to get access to file data (Content-Disposition
) you should upload the file as MIME multipart (multipart/form-data
).
<一个href=\"http://www.strathweb.com/2012/08/a-guide-to-asynchronous-file-uploads-in-asp-net-web-api-rtm/\">Here我展示如何从HTML表单,JavaScript和从.net上传一些例子。
Here I showed some examples on how to upload from HTML form, Javascript and from .NET.
然后,您可以做这样的事情,这个例子检查PDF / DOC文件只有:
You can then do something like this, this example checks for pdf/doc files only:
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;
}
}
这篇关于从Htt的prequestMessage内容文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!