Uploading and Viewing Photos - asp.net-mvc

Can anyone help i'm using MVC 5 and doing a code on uploading and displaying photos and i'm having an error (The name ' file ' does not exist in the current content) please help
This is the controller i'm using:
public class UploadController : Controller
{
private DataContext db = new DataContext();
public ActionResult Index()
{
var model = new UploadViewModel();
return View(model);
}
[HttpPost]
public ActionResult Upload(UploadViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
UploadDbModel fileUploadModel = new UploadDbModel();
try
{
if (file.ContentLength > 0)
{
byte[] uploadFile = new byte[model.File.InputStream.Length];
model.File.InputStream.Read(uploadFile, 0, uploadFile.Length);
fileUploadModel.FileName = model.File.FileName;
fileUploadModel.File = uploadFile;
db.UploadDbModels.Add(fileUploadModel);
db.SaveChanges();
}
return Content("FILE SUCCESSFULLY UPLOADED");
}
catch
{
return Content("UPLOAD FAILED");
}
}
public ActionResult Download()
{
return View(db.UploadDbModels.ToList());
}
public FileContentResult FileDownload(int? id)
{
byte[] fileData;
string fileName;
UploadDbModel fileRecord = db.UploadDbModels.Find(id);
fileData = (byte[])fileRecord.File.ToArray();
fileName = fileRecord.FileName;
return File(fileData, "text", fileName);
}
}

In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
[HttpPost]
public ActionResult Upload(UploadViewModel model, HttpPostedFileBase file)
{
if (file != null)
{
int byteCount = file.ContentLength; <---Your file Size or Length
.............
.............
}
}

Try and use system.web, just add the reference on the assembly hope it works.

Related

No parameterless constructor defined for this object. when Iam trying to update image

net-Mvc5 I am Updating the Imagepath which already saved in a database but I am getting this Error
No parameterless constructor defined for this object.
// Parameter less Constructor::
public EditclassWorkController()
{
}
// Code For Index Controller:
public ActionResult Index(HttpPostedFile file)
{
return View();
}
// Code for update ImagePath :
[HttpPost]
public ActionResult Edit(tbl_classWork vehi,HttpPostedFile file)
{
SchoolERP db = new SchoolERP();
tbl_classWork imgToSave =
(
from imga in db.tbl_classWork
where imga.Classwork_id == vehi.Classwork_id
select imga
).First();
if (ModelState.IsValid)
{
if (vehi != null)
{
imgToSave.class_file = file.ContentType;
var binaryReader = new BinaryReader(file.InputStream);
imgToSave.class_file = binaryReader.ReadBytes(file.ContentLength).ToString();
binaryReader.Close();
}
TryUpdateModel(imgToSave);
db.SaveChanges();
return RedirectToAction("Index");
}
//No path Found return Else part:
else
{
return View(vehi);
}
}

Mvc5 Error Please :( [duplicate]

This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 5 years ago.
Hello Everybody Good day My English is not very good Poo Do not Look Mvc 5 New Start My Blog Site.
I got the error
I List Categories, I Provide Entrance to Other Areas
When I Select Photo When I Select Time
I uploaded the picture and I share the link. I am taking this mistake. Could you show me the way to this error? Thank you for your time
namespace MvcSite.Controllers
{
public class AdminMakaleController : Controller
{
MvcblogDb db = new MvcblogDb();
// GET: AdminMakale
public ActionResult Index()
{
var makale = db.Makale.ToList();
return View(makale);
}
// GET: AdminMakale/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AdminMakale/Create
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi");
return View();
}
// POST: AdminMakale/Create
[HttpPost]
public ActionResult Create(Makale makale, string Etiket, HttpPostedFile Foto)
{
if (ModelState.IsValid)
{
if (Foto != null)
{
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFoto/" + newfoto;
}
if (Etiket != null)
{
string[] etiketdizi = Etiket.Split(',');
foreach (var i in etiketdizi)
{
var yenietiket = new Etiket { EtiketAdi = i };
db.Etiket.Add(yenietiket);
makale.Etiket.Add(yenietiket);
}
}
db.Makale.Add(makale);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
// GET: AdminMakale/Edit/5
public ActionResult Edit(int id)
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makales.KategoriId);
return View(makales);
}
// POST: AdminMakale/Edit/5
[HttpPost]
public ActionResult Edit(int id, HttpPostedFile Foto, Makale makale)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (Foto != null)
{
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFOTO/" + newfoto;
makales.Baslik = makale.Baslik;
makales.İcerik = makale.İcerik;
makales.KategoriId = makale.KategoriId;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makale.KategoriId);
return View(makale);
}
}
// GET: AdminMakale/Delete/5
public ActionResult Delete(int id)
{
var makale = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makale == null)
{
return HttpNotFound();
}
return View(makale);
}
// POST: AdminMakale/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
foreach (var i in makales.Yorum.ToList())
{
db.Yorum.Remove(i);
}
foreach (var i in makales.Etiket.ToList())
{
db.Etiket.Remove(i);
}
db.Makale.Remove(makales);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Try to use a DropDownListFor instead of a DropdownList. The error you mention means that you are having NULL in the SelectListItem. You should create a list of ListItem in the DropDownList.
(I'm not sure if I'm correct or not. I'm just trying to help quickly.)

How to load second partialview after success inserted in first partialview?

I have a view named Register.cshtml and 2 partialview named _AddUser.cshtml And _UserList.cshtml.
When I run the project shows register.cshtml and _AddUser.cshtml load in view. I want to load _UserList partialview after success inserted in _AddUser partialview.
DefaultController:
public class DefaultController : Controller
{
UserRepository UR = new UserRepository();
Automation_DBEntities database = new Automation_DBEntities();
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Users user, HttpPostedFileBase file)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
///////////////////SaveImage
if (file != null)
{
if (user.UserImage != "no-photo.jpg")
{
if (System.IO.File.Exists(Server.MapPath("/image/UserImage/" + user.UserImage)))
System.IO.File.Delete(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.UserImage = Guid.NewGuid().ToString().Replace("-", "") + Path.GetExtension(file.FileName);
file.SaveAs(Server.MapPath("/image/UserImage/" + user.UserImage));
}
user.RegisterDate = DateTime.Now;
if (blUser.Add(user))
{
return PartialView("_UserList");//Inserted
}
else
{
}
}
else
{
}
}
[HttpGet]
public ActionResult AddUser()
{
return PartialView("~/Areas/Admin/Views/Shared/_AddUser.cshtml");
}
[HttpGet]
public ActionResult UserList()
{
IQueryable<AutomationSystem.Models.DomainModel.Users> list = UR.Select();
return PartialView("~/Areas/Admin/Views/Shared/_UserList.cshtml", list);
}

RedirectToAction / save form and print PDF from on button

my application is MVC3 (ASPX views). I have a form, in the Edit view I have save button, that saves the form and return to the index page, and another button to print PDF from another ActionResult in the same controller as Edit; it there a way to save and print the PDF from one button?
Here is my script for edit view:
public ActionResult EditCTAH(long learnerID = 0, long caseListID = 0)
{
ViewBag.caseListID = (long)Session["_CTA_CaseListId"];
try
{
CTAHFormEdit ctform = _learnerscaseListsSvc.GetCTAHForm(learnerID, caseListID);
return View(ctform);
}
catch
{
return null;
}
}
[HttpPost]
public ActionResult EditCATH(CTAHFormEdit ctform)
{
if (ModelState.IsValid)
{
_learnerscaseListsSvc.EditCTAHForm(ctform);
long courseId = (long)Session["_CTA_CourseId"];
long caseId = (long)Session["_CTA_CaseId"];
long caselistId = (long)Session["_CTA_CaseListId"];
return RedirectToAction("Index", new { courseId = courseId, caseId = caseId, caselistId = caselistId });
}
return View(ctform);
}
and here is the script for printing the PDF:
public ActionResult EvaluationCATH_PDF(long learnerID = 0, long caseListID = 0)
{
try
{
.....
pdfStamper.Close();
byte[] byteInfo = workStream.ToArray();
SendPdfToBrowser(byteInfo, cth.Learner_ID, cth.StudyCase_ID);
return null;
}
catch
{
return null;
}
}
Thanks in advance.
If you want to get the PDF on the Save of your edit action, you may redirect to an action method which returns the PDF to browser
[HttpPost]
public ActionResult EditCATH(CTAHFormEdit ctform)
{
if (ModelState.IsValid)
{
//Saved succesfully, lets show the pdf in browser.
return RedirectToAction("Print",new { id=someIdValue});
}
return View(ctform);
}
public ActionResult Print(string id)
{
byte[] pdfByteArray=GetByteArrayFromPassedID(id);
return File(pdfByteArray,"application/pdf","somefriendlyname.pdf");
}

How to validate uploaded file in ASP.NET MVC?

I have a Create action that takes an entity object and a HttpPostedFileBase image. The image does not belong to the entity model.
I can save the entity object in the database and the file in disk, but I am not sure how to validate these business rules:
Image is required
Content type must be "image/png"
Must not exceed 1MB
A custom validation attribute is one way to go:
public class ValidateFileAttribute : RequiredAttribute
{
public override bool IsValid(object value)
{
var file = value as HttpPostedFileBase;
if (file == null)
{
return false;
}
if (file.ContentLength > 1 * 1024 * 1024)
{
return false;
}
try
{
using (var img = Image.FromStream(file.InputStream))
{
return img.RawFormat.Equals(ImageFormat.Png);
}
}
catch { }
return false;
}
}
and then apply on your model:
public class MyViewModel
{
[ValidateFile(ErrorMessage = "Please select a PNG image smaller than 1MB")]
public HttpPostedFileBase File { get; set; }
}
The controller might look like this:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The uploaded image corresponds to our business rules => process it
var fileName = Path.GetFileName(model.File.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
model.File.SaveAs(path);
return Content("Thanks for uploading", "text/plain");
}
}
and the view:
#model MyViewModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.LabelFor(x => x.File)
<input type="file" name="#Html.NameFor(x => x.File)" id="#Html.IdFor(x => x.File)" />
#Html.ValidationMessageFor(x => x.File)
<input type="submit" value="upload" />
}
Based on Darin Dimitrov's answer which I have found very helpful, I have an adapted version which allows checks for multiple file types, which is what I was initially looking for.
public override bool IsValid(object value)
{
bool isValid = false;
var file = value as HttpPostedFileBase;
if (file == null || file.ContentLength > 1 * 1024 * 1024)
{
return isValid;
}
if (IsFileTypeValid(file))
{
isValid = true;
}
return isValid;
}
private bool IsFileTypeValid(HttpPostedFileBase file)
{
bool isValid = false;
try
{
using (var img = Image.FromStream(file.InputStream))
{
if (IsOneOfValidFormats(img.RawFormat))
{
isValid = true;
}
}
}
catch
{
//Image is invalid
}
return isValid;
}
private bool IsOneOfValidFormats(ImageFormat rawFormat)
{
List<ImageFormat> formats = getValidFormats();
foreach (ImageFormat format in formats)
{
if(rawFormat.Equals(format))
{
return true;
}
}
return false;
}
private List<ImageFormat> getValidFormats()
{
List<ImageFormat> formats = new List<ImageFormat>();
formats.Add(ImageFormat.Png);
formats.Add(ImageFormat.Jpeg);
formats.Add(ImageFormat.Gif);
//add types here
return formats;
}
}
Here is a way to do it using viewmodel, take a look at whole code here
Asp.Net MVC file validation for size and type
Create a viewmodel as shown below with FileSize and FileTypes
public class ValidateFiles
{
[FileSize(10240)]
[FileTypes("doc,docx,xlsx")]
public HttpPostedFileBase File { get; set; }
}
Create custom attributes
public class FileSizeAttribute : ValidationAttribute
{
private readonly int _maxSize;
public FileSizeAttribute(int maxSize)
{
_maxSize = maxSize;
}
//.....
//.....
}
public class FileTypesAttribute : ValidationAttribute
{
private readonly List<string> _types;
public FileTypesAttribute(string types)
{
_types = types.Split(',').ToList();
}
//....
//...
}
And file length validation in asp.net core:
public async Task<IActionResult> MyAction()
{
var form = await Request.ReadFormAsync();
if (form.Files != null && form.Files.Count == 1)
{
var file = form.Files[0];
if (file.Length > 1 * 1024 * 1024)
{
ModelState.AddModelError(String.Empty, "Maximum file size is 1 Mb.");
}
}
// action code goes here
}
You may want to consider saving the image to database also:
using (MemoryStream mstream = new MemoryStream())
{
if (context.Request.Browser.Browser == "IE")
context.Request.Files[0].InputStream.CopyTo(mstream);
else
context.Request.InputStream.CopyTo(mstream);
if (ValidateIcon(mstream))
{
Icon icon = new Icon() { ImageData = mstream.ToArray(), MimeType = context.Request.ContentType };
this.iconRepository.SaveOrUpdate(icon);
}
}
I use this with NHibernate - entity defined:
public Icon(int id, byte[] imageData, string mimeType)
{
this.Id = id;
this.ImageData = imageData;
this.MimeType = mimeType;
}
public virtual byte[] ImageData { get; set; }
public virtual string MimeType { get; set; }
Then you can return the image as a FileContentResult:
public FileContentResult GetIcon(int? iconId)
{
try
{
if (!iconId.HasValue) return null;
Icon icon = this.iconRepository.Get(iconId.Value);
return File(icon.ImageData, icon.MimeType);
}
catch (Exception ex)
{
Log.ErrorFormat("ImageController: GetIcon Critical Error: {0}", ex);
return null;
}
}
Note that this is using ajax submit. Easier to access the data stream otherwise.

Resources