MVC 3 - 图像上传失败

时间:2011-03-15 15:34:20

标签: asp.net-mvc

我正在尝试编写一个允许用户将图像添加到数据库的程序,但它失败了。如果有人能帮助我,我将不胜感激...... 我的Index.cshtml文件包含以下代码......

 <td>
   @item.Picture1
   <img alt="@Html.Encode(item.Picture1)" src='@(Url.Action(("Picture1")) + 
    ToString())' width="64" height="64" />
</td>

Create.cshtml文件看起来像这样......

<div class="editor-field">
      @Html.EditorFor(model => model.Picture1)
      <input type="file" id="fileUpload" name="fileUpload" size="23"/>
      @Html.ValidationMessage("Picture1", "*")
</div>
<p>
     <input type="submit" value="Create" />
</p> 

在控制器中,对于Create,我有以下代码......

[HttpPost]
    public ActionResult Create([Bind(Exclude = "SubProductCategoryID")] SubProductCategory2 Createsubcat2, FormCollection values)
    {


        if (ModelState.IsValid)
        {
            if (Request.Files.Count > 0)
            {
             Createsubcat2.Picture1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[0]);
            }
            db.AddToSubProductCategory2(Createsubcat2);
            db.SaveChanges();
            return RedirectToAction("/");
        }
        PopulateProductCategoryDropDownList(Createsubcat2.ProductCategoryID);
        return View(Createsubcat2);
    }

    public FileResult Image(int id)
    {
        const string alternativePicturePath = @"/Content/question_mark.jpg";
        SubProductCategory2 product = db.SubProductCategory2.Where(k => k.SubProductCategoryID == id).FirstOrDefault();

        MemoryStream stream;

        if (product != null && product.Picture1 != null)
        {
            stream = new MemoryStream(product.Picture1);
        }
        else // If product cannot be found or product doesn't have a picture
        {
            stream = new MemoryStream();

            var path = Server.MapPath(alternativePicturePath);
            var image = new System.Drawing.Bitmap(path);

            image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            stream.Seek(0, SeekOrigin.Begin);
        }

        return new FileStreamResult(stream, "image/jpeg");
    }

FileHandler.cs

public class FileHandler
{
    /// <summary>
    /// Converts a HttpPostedFileBase into a byte array
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
    {
        int nFileLen = file.ContentLength;
        byte[] result = new byte[nFileLen];

        file.InputStream.Read(result, 0, nFileLen);

        return result;
    }    

提前致谢。我正在使用http://blog-dotnet.com/category/ASPNET-MVC.aspx网站作为参考。我在C#中使用VS 2010,ASP.NET 4.0,MVC 3。 SQL Server 2008R2。 SubProductCategory2表有文件Picture1,图像数据类型。

  

修改   实际上工作更多我有public byte [] Picture1 {get;组;在其中一个类中。我现在得到的输出是System.Byte [] System.Byte []。我该如何解决?

1 个答案:

答案 0 :(得分:1)

除了输入文件类型之外,还需要确保表单接受多部分数据......

<form method="POST" enctype="multipart/form-data" action="">

我看不到你的表单元素来确认你是否已经这样做了。