MVC获取图像的NULL路径

时间:2014-05-05 12:22:25

标签: asp.net-mvc asp.net-mvc-4 razor

我正在尝试将图像上传到我的App_Data文件夹。我使用了HttpPostedFileBase,但由于某种原因它总是返回null。 这是我的Create方法:

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult mkCreate(HttpPostedFileBase file)
    {
        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
            file.SaveAs(path);
        }
        return View();

    }

这是我的观点(Create.cshtml):

  @using (Html.BeginForm("mkCreate", "Resim", FormMethod.Post, new { enctype= "multipart/form-data" }))
{
    <table>
        <tr>
            <td>Image:</td>
            <td><input type="file" name="Images" id="Images" multiple /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="submit" value="Upload" /></td>
        </tr>
    </table>
}

你能帮我把图片上传到我的App_Data文件夹吗? 提前谢谢。

2 个答案:

答案 0 :(得分:1)

您的图片模型可能是这样的:

public class Image
{
    public IEnumerable<HttpPostedFileBase> Images { get; set; }
}

你的控制器应该有这样的动作:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Image image)
{
    foreach (var file in image.Images)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
                file.SaveAs(path);
            }
        }
    ViewBag.Message = "Image(s) uploaded successfully";
    return View();
 }

最后你的观点可能是这样的:

@model AppName.Models.Image

@{
  ViewBag.Title = "Index";
}

<h2>Image Upload Test</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype "multipart/form-data" }))
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
{
<table>
    <tr>
        <td>Image:</td>
        <td><input type="file" name="Images" id="Images" multiple /></td>
    </tr>
    <tr>
        <td>&nbsp;</td>
        <td><input type="submit" name="submit" value="Upload" /></td>
    </tr>
</table>
}

答案 1 :(得分:0)

尝试使用此添加enctype

public ActionResult Create(HttpPostedFileBase file)
{
//Rest of the code
}

查看

  @using (Html.BeginForm("YourMethod", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
           <input type="file" name="file" id="Images" multiple />
        }