在ASP.NET MVC中上传文件

当我选择一个文件并提交文件进行上传时,我无法获得模型中文件路径的值。 在Controller中,它显示为null 。 我究竟做错了什么?

视图

 

调节器

 public ActionResult Profile(ProfileModel model, FormCollection form) { string path = Convert.ToString(model.FilePath); return View(); } 

模型

 public HttpPostedFileBase FilePath { get { return _filePath; } set { _filePath = value; } } public bool UploadFile() { if (FilePath != null) { var filename = Path.GetFileName(FilePath.FileName); FilePath.SaveAs(@"C:\" + filename); return true; } return false; } 

我认为模型绑定不适用于HttpPostedFileBase

它应该可以工作,如果你从ViewModel中取出它并像这样做:

 public ActionResult Profile(HttpPostedFileBase filePath) { string path = Convert.ToString(filePath); return View(); } 

HTHS,
查尔斯

PS。 这篇文章可以帮助解释一下: ASP.NET MVC在参数为Model时发布了文件模型绑定

我没有VS来模拟你的问题。 所以我不确定答案。

试试这个,可能会奏效

  

如果不行,那么试试看你的formcollection和HttpContext.Request.Files

应该在那里。

我会使用IFormFile而不是使用HttpPostedFileBase

 public class ModelFile { ..... public string Path{ get; set; } public ICollection Upload { get; set; } } public async Task Index([Bind("Upload,Path")] ModelFile modelfile) { ... msg = await storeFilesInServer(modelfile.Upload,modelfile.Path); } private async Task storeFilesInServer(ICollection upload, string path) { Message msg = new Message(); msg.Status = "OK"; msg.Code = 100; msg.Text = "File uploaded successfully"; msg.Error = ""; string tempFileName = ""; try { foreach (var file in upload) { if (file.Length > 0) { string tempPath = path + @"\"; if (Request.Host.Value.Contains("localhost")) tempPath = path + @"\"; using (var fileStream = new FileStream(tempPath + file.FileName, FileMode.Create)) { await file.CopyToAsync(fileStream); tempFileName = file.FileName; } } msg.Text = tempFileName; } } catch (Exception ex) { msg.Error = ex.Message; msg.Status = "ERROR"; msg.Code = 301; msg.Text = "There was an error storing the files, please contact support team"; } return msg; }