【发布时间】:2013-06-04 04:33:02
【问题描述】:
我目前能够保存上传到 WebAPI 控制器的文件,但我希望能够将文件保存为具有正确文件扩展名的 guid,以便可以正确查看。
代码:
[ValidationFilter]
public HttpResponseMessage UploadFile([FromUri]string AdditionalInformation)
{
var task = this.Request.Content.ReadAsStreamAsync();
task.Wait();
using (var requestStream = task.Result)
{
try
{
// how can I get the file extension of the content and append this to the file path below?
using (var fileStream = File.Create(HttpContext.Current.Server.MapPath("~/" + Guid.NewGuid().ToString())))
{
requestStream.CopyTo(fileStream);
}
}
catch (IOException)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Created;
return response;
}
我似乎无法处理内容的实际文件名。我认为 headers.ContentDisposition.FileName 可能是候选人,但似乎没有人满。
【问题讨论】:
-
这是一个类似的问题,有一个答案 [stackoverflow.com/questions/14937926/… [1]: stackoverflow.com/questions/14937926/…
-
您能分享一下您的请求标头是什么样的吗?您是否在请求中填充了 ContentDisposition 标头?
-
设置此类标头是客户端的责任。你的客户是什么样的?
-
@Kiran:不,它没有被填充。此外,所有示例似乎都使用流提供程序来加载流。我想在不使用提供程序的情况下阅读它并使用 guid 和扩展名保存文件。不使用流提供程序的原因是它似乎不允许我返回为文件创建的 guid 调用函数。
标签: file-upload asp.net-web-api