Hi,
For your references:
- https://www.youtube.com/watch?v=9LPIu_BvatE
- https://www.youtube.com/watch?v=rpmtFvduwyI
Here I do for both save to database or (not and) to a folder, depend on it’s size:
A helper class, is used when save to database:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.IO;
namespace PersonEntity.Model
{
public static class ConvertFile
{
public static byte[] ImageToByte(HttpPostedFileBase imageFile)
{
if (imageFile == null) { return null; }
return (imageFile.ContentType == "image/jpeg" || imageFile.ContentType == "image/gif" || imageFile.ContentType == "image/png") ? FileToByte(imageFile) : null;
}
public static byte[] FileToByte(HttpPostedFileBase file)
{
byte[] data = new byte[file.ContentLength];
file.InputStream.Read(data, 0, file.ContentLength);
return data;
}
}
}
Need a partial class to the class where image class is defined, for "File":
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace PersonEntity.Model
{
[MetadataType(typeof(ProductPhotoMetadata))]
public partial class ProductPhoto
{
[DisplayFormat(NullDisplayText = "n/a")]
//[Required(ErrorMessage = "Please select image file")]
public HttpPostedFileBase File { get; set; }
}
}
Controller, add ",File" almost at the end of the "public Action Result:…….,File")] ProductPhoto…….. It si boleded and underlined
// GET: ProductPhotoes/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ProductPhoto productPhoto = db.ProductPhotoes.Find(id);
if (productPhoto == null)
{
return HttpNotFound();
}
return View(productPhoto);
}
// GET: ProductPhotoes/Create
public ActionResult Create()
{
ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria");
return View();
}
// POST: ProductPhotoes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
{
productPhoto.ModifiedDate = DateTime.Now;
if (productPhoto.File != null)
{
if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
{
ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
return View(productPhoto);
}
productPhoto.ImageSize = productPhoto.File.ContentLength;
/** Photo dibawh 61KB disimpan di database, sisanya disimpan di folder, dengan nama NewGuid() **/
if (productPhoto.File.ContentLength < 61676)
{
productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
}
else
{
productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
productPhoto.Photo = null;
var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
productPhoto.File.SaveAs(path);
}
}
if (ModelState.IsValid)
{
db.ProductPhotoes.Add(productPhoto);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
return View(productPhoto);
}
// GET: ProductPhotoes/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ProductPhoto productPhoto = db.ProductPhotoes.Find(id);
if (productPhoto == null)
{
return HttpNotFound();
}
ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
return View(productPhoto);
}
// POST: ProductPhotoes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Photo,PhotoFileName,ThumbnailUrl,LargePhoto,LargePhotoFileName,LargeUrl,ModifiedDate,ImageSize,Title,Caption,ProductPhotoCriteriaId,File")] ProductPhoto productPhoto)
{
productPhoto.ModifiedDate = DateTime.Now;
if (productPhoto.File != null)
{
if (productPhoto.File.ContentLength > (2 * 1024 * 1024) && productPhoto.File.ContentLength < 1)
{
ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
return View(productPhoto);
}
productPhoto.ImageSize = productPhoto.File.ContentLength;
if (productPhoto.File.ContentLength < 61676)
{
productPhoto.PhotoFileName = null;
productPhoto.Photo = ConvertFile.ImageToByte(productPhoto.File);
}
else
{
productPhoto.PhotoFileName = Guid.NewGuid() + Path.GetExtension(productPhoto.File.FileName); // productPhoto.File.FileName;
productPhoto.Photo = null;
var path = Path.Combine(Server.MapPath("~/images/normal"), productPhoto.PhotoFileName);
productPhoto.File.SaveAs(path);
}
}
if (ModelState.IsValid)
{
db.Entry(productPhoto).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProductPhotoCriteriaId = new SelectList(db.ProductPhotoCriterias, "Id", "Criteria", productPhoto.ProductPhotoCriteriaId);
return View(productPhoto);
}
Create.cshtml, attention on "@using (Html.BeginForm(…………………..))"
@model PersonEntity.Model.ProductPhoto
@{
ViewBag.Title = "Create: " + @EstateAgency.Admin.Resource.Product + " Photo";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("Create", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ProductPhoto</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.File, new { type = "file" })
@Html.ValidationMessage("CustomError")
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
<br />
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Edit.cshtml, attention on @using same with Create.cshtml:
@model PersonEntity.Model.ProductPhoto
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm("Edit", "ProductPhotoes", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ProductPhoto</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.Photo, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.File, new { type = "file" })
@Html.ValidationMessage("CustomError")
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PhotoFileName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ThumbnailUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ThumbnailUrl, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ThumbnailUrl, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LargePhoto, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LargePhoto, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LargePhoto, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LargePhotoFileName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LargePhotoFileName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LargePhotoFileName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LargeUrl, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LargeUrl, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LargeUrl, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ImageSize, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ImageSize, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Caption, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Caption, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Caption, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ProductPhotoCriteria.Criteria, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ProductPhotoCriteriaId", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ProductPhotoCriteriaId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
<br />
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
You may need to modify Web.config for larger file, add "maxRequestLength="2097152":
<system.web>
<globalization culture="auto" uiCulture="auto" />
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" maxRequestLength="2097152" />
</system.web>
Have fun