HttpPostedFileBase不接受文件

本文关键字:文件 不接受 HttpPostedFileBase | 更新日期: 2023-09-27 18:20:40

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

在创建了一个初始的MVC网站之后,我将API功能添加到了我的MVC项目中。不知道我是否错过了一些配置,但我的其他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请求时,它从来没有文件,因此它永远无法保存。

HttpPostedFileBase不接受文件

您可以从以下内容开始:

[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进行一些验证。例如,您可能需要检查内容长度。

那是ApiController吗?Web API中没有HttpPostedFile

您必须使用另一种方法:如何将文件发布到ASP.NET Web Api 2

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

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