I am trying write a program that allows users add a image to a database, but it fails. I would be grateful if someone could help me... My Index.cshtml file has the following code...
<td>
@item.Picture1
<img alt="@Html.Encode(item.Picture1)" src='@(Url.Action(("Picture1")) +
ToString())' width="64" height="64" />
</td>
Create.cshtml file looks like this...
<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>
In the controller, for Create, I have the following code...
[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();开发者_JS百科
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;
}
Thanks in advance. I am using http://blog-dotnet.com/category/ASPNET-MVC.aspx website for reference. I am using VS 2010, ASP.NET 4.0, MVC 3 in C#. SQL Server 2008R2. SubProductCategory2 table has file Picture1, image data type.
Edit: Actually working on more I have public byte[] Picture1 { get; set; } in one of the classes. The output I am now getting is System.Byte[] System.Byte[]. How do I fix this?
As well as having an input with a type of file, you need to make sure your form accepts multipart data...
<form method="POST" enctype="multipart/form-data" action="">
I couldn't see your form element to confirm whether you had done this.
精彩评论