【发布时间】:2018-08-28 21:39:26
【问题描述】:
我现在可以使用 MultipartFormDataStreamProvider 类从客户端接受文件,我得到 here 并能够根据文件名重命名文件。
问题是,我想忽略表单数据中不是我想要的字段。
例如,我只希望表单数据中的字段名称为 profilePic,其他字段的其余部分将被忽略。
问题是,不是我期望的文件被保存在服务器中。
我想删除这些文件。我该怎么做?
这是我的代码
[HttpPost]
[Route("api/topher/upload")]
public async Task<IHttpActionResult> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
return Content(HttpStatusCode.UnsupportedMediaType, new { message = "Set the content-type of header to multipart/form-data" });
}
string rootFolder = HttpContext.Current.Server.MapPath("~/App_Data");
MultipartFormDataStreamProvider streamProvider = new MyStreamProvider(rootFolder);
try
{
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (var key in streamProvider.FormData.AllKeys)
{
// the key is where the formdata keys is saved
// but the key of the file is not in here
}
foreach (MultipartFileData file in streamProvider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
// This is where the filepath of the files
// I want to delete the file that the key in the form-data is not profilePic
}
return Ok();
}
catch (Exception e)
{
return Ok(e);
}
}
【问题讨论】:
-
我将更新我的示例。谢谢
-
请分享您如何将文件传递到服务器。
标签: c# asp.net-web-api file-upload asp.net-web-api2 multipartform-data