2012-07-22 26 views
0

我试图让用户通过html表单上传图片,并且我想将它作为字节[]存储在我的模型中(将存储在数据库中)除非我应该使用其他字符而不是字节[]?MVC - 如何从HTML表单上传文件?

这是我的形式是什么样子

@using (Html.BeginForm()) { 
@Html.ValidationSummary(true) 

<fieldset> 
    <legend>ImageUploadModel</legend> 

    @Html.DisplayFor(model => model.Image) 
    <input type="file" name="Image" id="Image" accept="image/*" /> 

    @Html.DisplayFor(model => model.Caption) 
    @Html.EditorFor(model => model.Caption) 
    <p> 
     <input type="submit" value="Create" /> 
    </p> 
</fieldset> 

}

这里是我的控制器看起来像现在

[HttpPost] 
    public ActionResult Create(ImageUploadModel model) 
    { 
      // do stuff 

     return View(); 
    } 

这里是我的ImageUploadModel看起来像

public class ImageUploadModel 
{ 
    public Guid UploadedBy { get; set; } 

    [Display(Name = "Image")] 
    public byte[] Image { get; set; } 

    [Display(Name = "Image Caption")] 
    public string Caption { get; set; } 
} 

当我尝试上传文件时,出现一个关于不是有效base64string的错误。

什么是正确的方式来获得上传的文件,如MVC4一个byte []/C#

感谢

回答

1

更改表单标签像这样的(你可以用你的实际控制人名称替换YourControllerName

@using (Html.BeginForm("Create", "YourControllerName", 
      FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="Image" /> 
    <input type="file" name="Image" id="Image" 
    //your other form elements also 
} 

和 更改POST行动接受HttpPostedFileBase一个实例,并与同名为一体的input file元素

[HttpPost] 
public ActionResult Create(HttpPostedFileBase Image) 
{ 
     // do stuff 

    return View(); 
} 
+0

嗯,我只是试过,现在没有错误,但图像是空的。 – Kyle 2012-07-22 22:03:59

+0

@ user1308743:您需要更改表单以接受表单数据。看到我更新的答案。 – Shyju 2012-07-22 22:14:29

+0

谢谢=)现在作品 – Kyle 2012-07-23 19:39:23

0

您需要更改到HttpPostedFileBase