微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法保存从剃刀视图上传为 IForm 的文件的文件名

如何解决无法保存从剃刀视图上传为 IForm 的文件的文件名

我的目标是让用户文件上传到服务器,将文件保存在本地(在服务器上)并在模型中保留具有本地文件路径的属性,向用户返回不同的视图,然后返回模型仍然具有文件路径的控制器/服务器。 我的代码看起来像这样:

我的模型:

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 举报,一经查实,本站将立刻删除。