我如何从输入类型"文件"在ASP.. NET MVC项目

本文关键字:quot ASP NET MVC 项目 文件 输入 类型 | 更新日期: 2023-09-27 18:01:32

我是ASP新手。NET和我将非常感激,如果有人可以帮助。我有我的文件输入:

<form action="NewProject.cshtml" method="post" enctype="multipart/form-data">
<fieldset>
  <legend> Upload Image </legend>
  <label for="Image">Image</label>
  <input type="file" name="Image" id ="filename"/>
  <br/>
  <input type="submit" value="Upload" id="Add" />
</fieldset>

上传图片使用:

@{  WebImage photo = null;
var newFileName = "";
var imagePath = "";
if(IsPost){
    photo = WebImage.GetImageFromRequest();
    if(photo != null){
        newFileName = Guid.NewGuid().ToString() + "_" +
            Path.GetFileName(photo.FileName);
        imagePath = @"Images'" + newFileName;
        photo.Save(@"~'" + imagePath);
//an attempt
       PoleInvestProject.Models.Project project = new PoleInvestProject.Models.Project();
            project.Image = imagePath; //storing in model property Image
        }
    }
}

现在我需要从那里获得图像的路径,并将其与我的模型相关联,该模型具有属性public string Image { get; set; }。我想通过DBContext context将这个文件路径存储在数据库中。

  context.Projects.Add(new Project()
            {
                Image = model.Image
            });
            context.SaveChanges();

但是这给了我NULL,我的数据库表中没有Projects。我做错了什么?提前感谢!

我如何从输入类型"文件"在ASP.. NET MVC项目

在您的模型中创建一个新的属性,并将其命名为FileName。现在,在视图中创建一个同名的隐藏文件

<input type="hidden" id="FileName" value="" />

添加一个更改句柄到文件输入

<input type="file" onchange="document.getElementById('FileName').value = this.value;" />

这将在每次更改文件名时用文件名的值更新隐藏文件。当您进行回发时,模型绑定器将完成其余的工作,并且您将在模型中拥有文件的名称。文件名

希望能有所帮助