问题描述
我的目标是让用户将文件上传到服务器,将文件保存在本地(在服务器上)并在模型中保留具有本地文件路径的属性,向用户返回不同的视图,然后返回模型仍然具有文件路径的控制器/服务器。 我的代码看起来像这样:
我的模型:
public class MyModel
{
public IFormFile MyFile { get; set; }
public string LocalFilePath { get; set; }
public void copyFileLocally(ref string err)
{
try
{
var stream = System.IO.File.Create($"PathToSaveFile/{this.MyFile.FileName}");
stream.Position = 0;
this.DatFile.copyTo(stream);
stream.Flush();
this.LocalFilePath = $"PathToSaveFile/{this.MyFile.FileName}";
}
catch (Exception ex)
{
err = ex.Message;
return;
}
}
}
我的控制器:
public class MyController
{
public IActionResult UploadFile(MyModel model)
{
string err = null;
model.copyFileLocally(ref err);
if (err != null)
{
return Json(err);
}
return View("View2",model);
}
Public Void DoSomething(MyModel model)
{
// does something with model.LocalFilePath
}
}
观看次数:
View1:
@model MyModel
@using (Html.BeginForm("UploadFile","MyController",FormMethod.Post,new { enctype = "multipart/form-data" }))
{
<!---does a bunch of stuff and assigns a bunch of members--->
@Html.TextBoxFor(model => model.MyFile,null,new { @type = "file",@class = "input-file",@enctype = "multipart/form-data" })
<input type="submit" value="Send"/>
}
View2:
@model MyModel
@using (Html.BeginForm("DoSomething",FormMethod.Post ))
{
<!-- does a bunch of stuff and creates a bunch of hidden TextBoxFor elements to reassign model properties including file name as seen below--->
@Html.TextBoxFor(model => model.LocalFilePath,new { @hidden = "hidden" })
<input type="submit" value="Send"/>
}
问题是一旦调用了 DoSomething 函数,所有其他属性都会被分配,只有 LocalFilePath 属性为空。知道为什么吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)