将HttpPostedFileBase传递给控制器方法

本文关键字:控制器 方法 HttpPostedFileBase | 更新日期: 2023-09-27 18:26:19

我只是想创建一个可以输入名称并上传文件的表单。这是视图模型:

public class EmployeeViewModel
{
    [ScaffoldColumn(false)]
    public int EmployeeId { get; set; }
    public string Name { get; set; }
    public HttpPostedFileBase Resume { get; set; }
}

我的观点:

@using (Html.BeginForm("Create", "Employees", FormMethod.Post))
{   
    @Html.TextBoxFor(model => model.Name)
    @Html.TextBoxFor(model => model.Resume, new { type = "file" })
    <p>
        <input type="submit" value="Save" />
    </p>
    @Html.ValidationSummary()
}

我的控制器方法:

[HttpPost]
public ActionResult Create(EmployeeViewModel viewModel)
{
    // code here...
}

问题是,当我发布到控制器方法时,Resume属性为null。Name属性可以很好地传递,但不会传递HttpPostedFileBase。

我是不是做错了什么?

将HttpPostedFileBase传递给控制器方法

将enctype添加到表单中:

@Html.BeginForm("Create", "Employees", FormMethod.Post, 
                 new{ enctype="multipart/form-data"})

请以类似的形式添加编码类型

@using (Html.BeginForm("Create","Employees",FormMethod.Post, new { enctype = "multipart/form-data" }))

通过以下代码以视图的形式添加编码类型:

@using (Html.BeginForm("Create", "Employees", FormMethod.Post,new{ enctype="multipart/form-data"}))
{   
     @Html.TextBoxFor(model => model.Name)
     @Html.TextBoxFor(model => model.Resume, new { type = "file" })
    <p>
    <input type="submit" value="Save" />
    </p>
@Html.ValidationSummary()
}

在您各自的控制器中添加以下代码

[HttpPost]
public ActionResult Create(EmployeeViewModel viewModel)
{
       if (Request.Files.Count > 0)
        {
            foreach (string file in Request.Files)
            {
                string pathFile = string.Empty;
                if (file != null)
                {
                    string path = string.Empty;
                    string fileName = string.Empty;
                    string fullPath = string.Empty;
                    path = AppDomain.CurrentDomain.BaseDirectory + "directory where you want to upload file";//here give the directory where you want to save your file
                    if (!System.IO.Directory.Exists(path))//if path do not exit
                    {
                        System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "directory_name/");//if given directory dont exist, it creates with give directory name
                    }
                    fileName = Request.Files[file].FileName;
                    fullPath = Path.Combine(path, fileName);
                    if (!System.IO.File.Exists(fullPath))
                    {
                        if (fileName != null && fileName.Trim().Length > 0)
                        {
                            Request.Files[file].SaveAs(fullPath);
                        }
                    }
                }
            }
        }
}

我指定的路径将在basedirectory的目录内。。。。您可以提供自己想要保存文件的路径