我有一个post方法,其中有一个文件上传控件。要在控制器中获取上传的文件,我收到如下错误:
Error CS1061 'HttpRequest' does not contain a definition for 'Files' and no extension method 'Files' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)
我的代码如下:
[ValidateAntiForgeryToken]
[HttpPost]
public async Task<IActionResult> TeamUserDetail(TeamUsers model)
{
var file = Request.Files[0];
return View();
}
在Request.Files [0],它给出了上面显示的错误。 MVC6用于项目。
请指导我。我错过了添加的任何参考吗?
谢谢
答案 0 :(得分:3)
MVC 6使用另一种机制上传文件。您可以在GitHub或other sources上获得更多示例。只需使用IFormFile
作为操作的参数:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}
[HttpPost]
public async Task<IActionResult> UploadMultiple(ICollection<IFormFile> files)
{
var uploads = Path.Combine(_environment.WebRootPath,"uploads");
foreach(var file in files)
{
if(file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
await file.SaveAsAsync(Path.Combine(uploads,fileName));
}
return View();
}
}
您可以在asp.net sources中看到IFormFile
的当前合约。