C# Web API 2 - 忽略具有不同字段名称的文件上传

C# Web API 2 - Ignore file uploads with different field name

我现在可以使用 MultipartFormDataStreamProvider class 接受来自客户端的文件 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);
    }
}

您可以使用file.Headers.ContentDisposition.Name

获取表单中的字段名称
<input name="profilePic" type="file" />

foreach你可以检查如下

if (file.Headers.ContentDisposition.Name == "profilePic")
{
   // delete the file
}