【问题标题】:HttpPostedFileBase not accepting fileHttpPostedFileBase 不接受文件
【发布时间】:2015-11-05 20:02:43
【问题描述】:

我有一个需要接受文件的 API 方法。我正在使用 Postman chrome 插件来调用 api 并附加文件。

在创建初始 MVC 网站后,我向我的 MVC 项目添加了 API 功能。不知道我是否错过了一些配置,但我的其他 API 调用只是这个没有得到任何文件。

这是代码

[Route("~/api/mediaitems/{token}/{eventId}")]
    public async Task<HttpResponseMessage> MediaItems(string token, int eventId, HttpPostedFileBase upload)
    {
        if (upload.ContentLength > 0)
        {
            string _targetFolder = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FilePath"]);
            string _targetPath = Path.Combine(_targetFolder, Guid.NewGuid() + Path.GetFileName(upload.FileName));
            upload.SaveAs(_targetPath);

            var mediaItem = new MediaItem
            {
                MediaFilePath = _targetPath,
                FileType = upload.FileName,
                EventId = eventId,
                CreatedDate = DateTime.Now.Date
            };

            //Save mediaItem
            _repo.SaveMediaItem(mediaItem);

            return Request.CreateResponse(HttpStatusCode.Created);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }           
    }

http://localhost:24727/api/mediaitems/12341254234/1

这是 URL,然后我将 .jpg 附加到邮递员正文。 当我运行 api 请求时,它永远不会有文件,因此它永远无法保存。

【问题讨论】:

  • 您可以尝试使用一个小文件(包含一堆字符的文本文件)并使用 chrome 开发人员工具或 fiddler 在此处查看并复制请求正文。
  • 你调试代码了吗? MediaItems 被调用了吗? upload.ContentLength &gt; 0 的哪个分支被执行?
  • 上传时出现空引用异常,当我将 if (upload != null && upload.C​​ontentLength > 0) 添加到 if (upload.C​​ontentLength > 0) 时,它只是跳过并返回一个错误请求,这意味着没有 HttpPostedFileBase
  • 您能描述一下您在 Postman 中用于附加文件的步骤吗?
  • 我插入 URL,选择 POST,然后转到我添加文件的正文。试过 .txt 和 .png

标签: c# asp.net-mvc api rest


【解决方案1】:

你可以这样开始:

[Route("~/api/mediaitems/{token}/{eventId}")]
public async Task<HttpResponseMessage> MediaItems(string token, int eventId)
{
    byte[] data = await this.Request.Content.ReadAsByteArrayAsync();

    //data will contain the file content, you can save it here

    return Request.CreateResponse(HttpStatusCode.Created);
}

注意我是如何删除HttpPostedFileBase upload 参数的。

如果需要,您可以根据this.Request.Content 进行一些验证。例如,您可能想要检查内容长度。

【讨论】:

  • 如果我这样做,我确实会收到数据,但我将如何将其保存到具有文件名的文件夹中?
【解决方案2】:

那是ApiController 吗? Web API 中没有HttpPostedFile

你必须使用另一种方法:How to post file to ASP.NET Web Api 2

【讨论】:

  • 它是一个 API 控制器,我还有其他 API 调用可以工作。
【解决方案3】:

也许可以帮助...将以下内容添加到 web.config。您必须设置最大可接受的文件大小(以字节为单位):15728640 = 15MB

<configuration>    
    <location path="Custommer/edit">
    <system.web>
      <httpRuntime maxRequestLength="15728640"/>
    </system.web>
  </location>
</configuration>

【讨论】:

    猜你喜欢
    • 2020-03-09
    • 2014-09-10
    • 2020-02-04
    • 2014-10-17
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多