【问题标题】:C# Web API 2 - Ignore file uploads with different field nameC# Web API 2 - 忽略具有不同字段名称的文件上传
【发布时间】: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


【解决方案1】:

您可以使用file.Headers.ContentDisposition.Name获取表单中的字段名称

<input name="profilePic" type="file" />

foreach你可以检查如下

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

【讨论】:

  • 抓得好兄弟。这就是我要找的。现在我可以删除没有profilePic字段名称的上传文件
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-31
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 2017-12-19
相关资源
最近更新 更多