我有一个需要接受文件的API方法。我使用Postman Chrome插件来调用api并附加一个文件。HttpPostedFileBase不接受文件
在创建初始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开发者工具或小提琴手看到并复制到这里了请求正文。 –
你调试过代码吗?是否调用MediaItems? 'upload.ContentLength> 0'的哪个分支被执行? –
我得到一个空引用异常上传,当我添加if(upload!= null && upload.ContentLength> 0)if(upload.ContentLength> 0)它只是跳过并返回一个错误的请求,这意味着没有HttpPostedFileBase – Sl1ver