带有多个属性的MVC文件上传

本文关键字:MVC 文件 属性 | 更新日期: 2023-09-27 18:09:03

有解释如何在MVC中上传文件的链接,但其中大多数只有一个输入字段(文件),没有其他内容,它与以下控制器代码一起工作:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
...

1)如果我有一个具有多个属性的ViewModel,并且该文件是必填字段之一,我该怎么办?

public class MyViewModel
{
    // ...other properties...
    // debug value: {string[1]} = "<filename-without-path>"
    public object File { get; set; }
}

调试时,File的值是带有文件名的{string[1]},但没有路径。我不知道该怎么办。我甚至试图使文件类型为HttpPostedFileBase,但这不起作用。

2)另一个问题是,它"忘记"文件名,例如,当有其他验证错误,应该修复。

带有多个属性的MVC文件上传

您需要在您的模型中创建属性:

public class ViewModel
{
    public string ImagePath{ get; set; }
.....

}

编辑视图:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new 
                                       { enctype = "multipart/form-data" }))
{
    <label for="ImageUpload">Filename:</label>
    <input type="file" name="ImageUpload" id="ImageUpload" />
}
在控制器:

[HttpPost]
public ActionResult Upload(ViewModel model)
{
    if (ModelState.IsValid)
    {
        var file = Request.Files["ImageUpload"];
        if (file != null && file.ContentLength > 0){
            var uploadDir = "~/uploads"
            var imagePath = Path.Combine(Server.MapPath(uploadDir), file.FileName);
            var imageUrl = Path.Combine(uploadDir, file.FileName);
            file.SaveAs(imagePath);
            model.ImagePath= imageUrl;
        }
    }
}

1)参见:https://stackoverflow.com/a/10757754/371917

表单必须有enctype = "multipart/form-data",然后我可以将属性类型设置为HttpPostedFileBase

Web:

@using (Html.BeginForm("Create", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    ... modified from generated data ...
    <div class="form-group">
        @Html.LabelFor(model => model.File, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.File, new { type = "file" })
            @Html.ValidationMessageFor(model => model.File)
        </div>
    </div>
}
c#:

public class MyViewModel
{
    [Required]
    public HttpPostedFileBase File { get; set; }
}

2)当有其他验证错误时,我仍然不知道如何阻止它"忘记"文件是什么…