我有一個需要接受文件的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