MVC Img to Byte []

时间:2014-02-24 22:02:34

标签: asp.net-mvc file-upload download

我的模特

partial class Company
{
    ... More Properties
    public HttpPostedFileBase FilePicture { get; set; }
    public byte[] Picture { get; set; }
}

我的控制器

[HttpPost]
public ActionResult Edit(int id, Models.Company model)
{
    if(model.FilePicture != null)
    {
        using(Stream inputStream = model.FilePicture.InputStream)
        {
            MemoryStream memoryStream = inputStream as MemoryStream;
            if(memoryStream == null)
            {
                memoryStream = new MemoryStream();
                inputStream.CopyTo(memoryStream);
            }
            model.Picture = memoryStream.ToArray();
        }
    }
    //EditDefault does the persisting
    return this.EditDefault(id, model);
}

我的观点

@using (Html.BeginForm("Edit", currentController, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    //Clicks on the Picture and the Upload butten are forwarded to the file input tag
    //readUrl sets the image as sone as the file changes
    <input id="filePicture" type="file" name="filePicture" onchange="readURL(this);">

    <button type="button" id="pictureUploadBtnPicture" onclick="$('#filePicture').click();"> Upload</button>

    //ClearImg clears the img tag and resets the file input tag
    <button type="button" id="pictureDeleteBtnPicture" onclick="clearimg(this);"> Delete</button>

    ...if Picture not null
    ...{
        <img id="PicturePicture" src="data:image/png;base64,@System.Convert.ToBase64String(@Model.Picture.ToArray())">

        <input type="hidden" value="@System.Convert.ToBase64String(@Model.Picture.ToArray())" name="Picture"> **added** 
    ...}
    ...else ... Render empty Picture and set it per javascript

    <input type="submit" value="Safe" class="btn btn-primary">
}

我有一个Form,其中包含一些属性,如name,city,...和包含图片数据的byte []。上传,显示和删除正在运行。我现在的问题是,当我改变某些东西并且我再次保护网站时,Picture Property在模型中为空,我在Post Action中得到了。我猜有些东西不适用于映射。

为了清楚,我希望img映射到byte []。

提前获得任何帮助:)

更新

向Matt Tabor致谢;)

添加了隐藏的输入字段,现在我在控制器中获取它。

如果有人需要,请更新视图。

1 个答案:

答案 0 :(得分:1)

<img id="Picture" name="Picture" src="data:image/png;base64,@System.Convert.ToBase64String(@Model.Picture.ToArray())">

此属性不是输入,当您将其提交给服务器时,它不会对图像进行求和。

你必须使用类似存储字节数组的隐藏输入。

尝试在您的图片代码

下添加此内容
@Html.HiddenFor(m=>m.Picture)