ASP.Net MVC 2图片上传

时间:2011-01-25 14:20:06

标签: asp.net-mvc-2

我正在尝试使用MVC2进行简单的图像上传。在我看来,我有:

<% using (Html.BeginForm("Upload","Home")) { %> 
    <input type="file" name="upload" id="ImageUpload" value="Upload Image"/>
    <input type="submit" value="Upload" />
<% } %>

在我的控制器(Home)中,如何上传此图像并将其保存到数据库?我是ASP.Net MVC的新手,这件事让我陷入困境。提前感谢您的帮助和时间。


修改

好吧,我想我的答案含糊不清,我要提供更多详细信息,这就是我所拥有的:

图像模型很简单,如下所示 -

public class ImageModel
{
    public Image image;
    public string ImageName;

    public ImageModel(Image image, string name)
    {
        this.image = image;
        ImageName = name;
    }

}

视图是这样的:

<%using (Html.BeginForm("Upload","Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{%>    
    <input type="text" id="ImageName" />
    <input type="file" name="upload" id="ImageUpload" value="Upload Image"/>
    <input type="submit" value="Upload" />
<%} %>

控制器是我想要创建一个新的ImageModel实例,验证它并且如果有效将它保存到数据库:所以我有:

    public ActionResult Upload(ImageModel image)
    {
        //this is where i am stuck?
        //how to get the supplied image as part of the ImageModel object
        //whats the best way to retrieve the supplied image

        ImageModel temp = image;
        if(!temp.IsValid()){
            //get errors

            //return error view
        }
        uploadrepository.SaveImage(temp);     

        return View();
    }

问题是如何获取提供的图像并将其保存到数据库

1 个答案:

答案 0 :(得分:0)

根据您的View代码尝试将模型更改为此...

public class ImageModel
{
    public HttpPostedFileWrapper upload { get; set; }
    public string ImageName { get; set; } 
}

另外,您需要命名该文本输入元素(而不仅仅是id)......

<input type="text" id="ImageName" name="ImageName" />