Asp.Net MVC File Upload/Update ( Both Image And .Pdf Etc ) With ...

Skip to content Search Gists Search Gists All gists Back to GitHub Sign in Sign up Sign in Sign up Dismiss alert {{ message }}

Instantly share code, notes, and snippets.

@Balii06 Balii06/Product.cs Created June 2, 2019 17:54 Show Gist options
  • Star (0) You must be signed in to star a gist
  • Fork (2) You must be signed in to fork a gist
  • Embed Select an option
    • Embed Embed this gist in your website.
    • Share Copy sharable link for this gist.
    • Clone via HTTPS Clone using the web URL.

    No results found

    Learn more about clone URLs Clone this repository at <script src="https://gist.github.com/Balii06/f7d2d53004e309be70d599fda36f8bef.js"></script>
  • Save Balii06/f7d2d53004e309be70d599fda36f8bef to your computer and use it in GitHub Desktop.
Code Revisions 1 Forks 2 Embed Select an option
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.

No results found

Learn more about clone URLs Clone this repository at <script src="https://gist.github.com/Balii06/f7d2d53004e309be70d599fda36f8bef.js"></script> Save Balii06/f7d2d53004e309be70d599fda36f8bef to your computer and use it in GitHub Desktop. Download ZIP Asp.Net MVC File Upload/Update ( Both Image and .Pdf etc ) with Validation using Tailwind css utilities Raw Product.cs This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters
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; }
}
}
Raw ProductAdd.cshtml This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters
@model ImageFile_Upload.Models.Product
@{
ViewBag.Title = "ProductAdd";
var Message = ViewBag.Message;
}
<head>
<title></title>
<link href="~/Content/tailwind.min.css" rel="stylesheet" />
</head>
<body>
@using (Html.BeginForm("ProductAdd","Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@if(Message != null)
{
<div role="alert">
<div class="bg-red-500 text-white font-bold rounded-t px-4 py-2">
Danger
</div>
<div class="border border-t-0 border-red-400 rounded-b bg-red-100 px-4 py-3 text-red-700">
<p>@Message</p>
</div>
</div>
}
<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>
}
</body>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Raw ProductController.cs This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters
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);
}
}
}
}
@alikopter Copy link

alikopter commented Sep 7, 2022

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); } } }

}

Uh oh!

There was an error while loading. Please reload this page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment You can’t perform that action at this time.

Từ khóa » Html.editorfor Image Upload