具有多个属性的MVC文件上载

时间:2014-06-17 14:18:41

标签: c# asp.net-mvc

有解释how to upload a file in 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)另一个问题是它“忘记”文件名,例如当还有其他验证错误应该修复时。

2 个答案:

答案 0 :(得分:1)

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

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 :(得分:0)

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

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

网络:

@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)我仍然不知道如何阻止&#34;忘记&#34;当存在其他验证错误时文件是什么......