Reputation: 11
I have create an application to upload image in database this is my model
[Table("ImageGallery")]
public class ImageGallery
{
[Key]
public int ImageID { get; set; }
public int ImageSize { get; set; }
public string FileName { get; set; }
public byte[] ImageData { get; set; }
[Required(ErrorMessage="Please select Image File")]
public HttpPostedFileBase file { get; set; }
}
this is my database model
public class TPADB : DbContext
{
public DbSet<ImageGallery> imagegallery { get; set; }
}
this is my view
@using (Html.BeginForm("Upload", "ImageUP", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<table>
<tr>
<td>Select File : </td>
<td>
@Html.TextBoxFor(Model => Model.file, new { type="file"})
@Html.ValidationMessage("CustomError")
</td>
<td>
<input type="submit" value="Upload" />
</td>
</tr>
</table>
}
this is my controller
[HttpGet]
public ActionResult Upload()
{
return View();
}
[HttpPost]
public ActionResult Upload(ImageGallery IG)
{
IG.FileName = IG.file.FileName;
//IG.ImageSize = IG.file.ContentLength;
byte[] data = new byte[IG.file.ContentLength];
IG.file.InputStream.Read(data, 0, IG.file.ContentLength);
IG.ImageData = data;
using (TPADB db = new TPADB())
{
db.imagegallery.Add(IG);
db.SaveChanges();
}
return View();
}
but it throughs an error that "One or more validation errors were detected during model generation:
TPA.Models.HttpPostedFileBase: : EntityType 'HttpPostedFileBase' has no key defined. Define the key for this EntityType. HttpPostedFileBases: EntityType: EntitySet 'HttpPostedFileBases' is based on type 'HttpPostedFileBase' that has no keys defined."
Upvotes: 1
Views: 1305
Reputation: 21
Figured it out, make the following changes to the model:
public partial class ImageGallery
{
[Key]
public int ImageID { get; set; }
public int ImageSize { get; set; }
public string FileName { get; set; }
public byte[] ImageData { get; set; }
public string File
{
get
{
string mimeType = "image/png";
string base64 = Convert.ToBase64String(ImageData);
return string.Format("data:{0},{1}", mimeType, base64);
}
}
}
Then add this line to the controller:
HttpPostedFileBase File = Request.Files[0];
Replace any IG.File entry with File for example:
if (File.ContentLength > (2 * 1024 * 1024))
Upvotes: 1