Loading, please wait...

A to Z Full Forms and Acronyms

File (Img/Pdf) Upload Using Code First Approach

May 29, 2019 Asp.Net MVC , C#, 2873 Views
Multiple File Upload/Update Using Asp.Net MVC Code First ApproachWith Validation (Img Ext./ Pdf Ext.) (File Size)

 Product.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ImageFile_Upload.Models
{
public class Product
{
[Key]
public int ProductId { get; set; }

[Display(Name = "Product Name")]
public string ProductName { get; set; }

[Display(Name = "Product Image")]
public string Image { get; set; }

[Display(Name = "File")]
public string Pdf { get; set; }
}
}

 

 ProductController

 

using ImageFile_Upload.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace ImageFile_Upload.Controllers
{
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
return View();
}

[HttpGet]
public ActionResult ProductAdd()
{
return View();
}

[HttpPost]
public ActionResult ProductAdd(Product product, IEnumerable<HttpPostedFileBase> file, int?id)
{
if (ModelState.IsValid)
{
var supportedPicTypes = new[] { "jpg", "jpeg", "png" };
var supportedPdfTypes = new[] { "pdf", "doc", "docx"};
var PicFileSize = 200000;
var PdfFileSize = 1000000;

if (file.ElementAt(0) != null && file.ElementAt(1) != null)
{
if (file.ElementAt(0).ContentLength > (PicFileSize))
{
ViewBag.Message = "Image Size should be less than 2mb";
}
else if(!supportedPicTypes.Contains(System.IO.Path.GetExtension(file.ElementAt(0).FileName).Substring(1)))
{
ViewBag.Message = "Image Extension is not valid";
}
else if(file.ElementAt(1).ContentLength > (PdfFileSize))
{
ViewBag.Message = "File Size should be less than 10mb";
}
else if (!supportedPdfTypes.Contains(System.IO.Path.GetExtension(file.ElementAt(1).FileName).Substring(1)))
{
ViewBag.Message = "File Extension is not valid";
}
else
{
using (MyDbContext db = new MyDbContext())
{

var produc = db.products.Where(x => x.ProductId == id).FirstOrDefault();
if (produc != null)
{
ViewBag.Message = "Record Already Exist!";
string Upath = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.ElementAt(0).FileName));
file.ElementAt(0).SaveAs(Upath);

string Upth = Path.Combine(Server.MapPath("~/PdfFiles"), Path.GetFileName(file.ElementAt(1).FileName));
file.ElementAt(1).SaveAs(Upth);

Product p = new Product
{
ProductId = (int)id,
ProductName = product.ProductName,
Image = "~/Images/" + file.ElementAt(0).FileName,
Pdf = "~/PdfFiles/" + file.ElementAt(1).FileName
};
db.Entry(produc).CurrentValues.SetValues(p);
db.SaveChanges();
ViewBag.Message = "Record Already Exist!";

}
else
{
string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.ElementAt(0).FileName));
file.ElementAt(0).SaveAs(path);

string pth = Path.Combine(Server.MapPath("~/PdfFiles"), Path.GetFileName(file.ElementAt(1).FileName));
file.ElementAt(1).SaveAs(pth);

db.products.Add(new Product
{
ProductId = product.ProductId,
ProductName = product.ProductName,
Image = "~/Images/" + file.ElementAt(0).FileName,
Pdf = "~/PdfFiles/" + file.ElementAt(1).FileName
});
db.SaveChanges();
ViewBag.Message = "Uploaded Successfully";
}
}
}
}
else
{
ViewBag.Message = "File Not Found";
}
}
return View();
}

public ActionResult Show()
{
using (MyDbContext db = new MyDbContext())
{
List<Product> product = db.products.ToList();
return View(product);
}
}
}
}

View(Add/Update, Show)



@model ImageFile_Upload.Models.Product

@{
ViewBag.Title = "ProductAdd";
var Message = ViewBag.Message;
}

<div class="message-success">@Message</div>

<h2>ProductAdd</h2>


@using (Html.BeginForm("ProductAdd","Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Product</h4>
<hr />
@Html.ValidationSummary(true)

<div class="form-group">
@Html.LabelFor(model => model.ProductName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ProductName)
@Html.ValidationMessageFor(model => model.ProductName)
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Image, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="file" id="picfile" /> <br /><br />
@Html.ValidationMessageFor(model => model.Image)
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Pdf, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="file" id="pdffile" /> <br /><br />
@Html.ValidationMessageFor(model => model.Pdf)
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Upload/Update" class="btn btn-default" />
</div>
</div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}




--------------------------------------------------------------------------------SHOW-------------------------------------------------------------------------------------




@model IEnumerable<ImageFile_Upload.Models.Product>

@{
ViewBag.Title = "Show";
}

<h2>Show</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.ProductName)
</th>
<th>
@Html.DisplayNameFor(model => model.Image)
</th>
<th>
@Html.DisplayNameFor(model => model.Pdf)
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
<img src="@Url.Content(item.Image)" alt="Image" height="50" width="50" />
</td>
<td>
<embed src="@Url.Content(item.Pdf)" height="200" width="200" />
</td>
<td>
@Html.ActionLink("Edit", "ProductAdd", new { id=item.ProductId }) |
@Html.ActionLink("Details", "Details", new { id=item.ProductId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProductId })
</td>
</tr>
}

</table>
A to Z Full Forms and Acronyms

Related Article