Save Image to server and reference it via a web address, MVC - c#

When uploading an image it should save to the server which I've accomplished, however I want it to also save to my sql database as a web address so that I can reference the image outside of my application. So I basically want it to upload to the server and then save to the database path as url: "\admin.loyaltyworx.co.za\Images\ImageName"
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CustomerID,DiscountLevelID,LoyaltyLevelID,CustomerCompanyName,CustomerName,CustomerSurname,CustomerGUID,CustomerStatus,CustomerAddress,CustomerTel,CustomerCel,CustomerNumber,CustomerContact,CustomerLogo,CustomerLogoPath,LastStoreCustomerSyncID")] Customer customer, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if(file!=null)
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Images/");
if (!Directory.Exists(physicalPath))
Directory.CreateDirectory(physicalPath);
string physicalFullPath = Path.Combine(physicalPath, ImageName);
file.SaveAs(physicalFullPath);
customer.CustomerLogo = ImageName;
customer.CustomerLogoPath = physicalFullPath;
db.Entry(customer).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
ViewBag.LoyaltyLevelID = new SelectList(db.LoyaltyLevels, "LoyaltyLevelID", "LoyaltyLevelName", customer.LoyaltyLevelID);
ViewBag.DiscountLevelID = new SelectList(db.DiscountLevels, "DiscountLevelID", "DiscountLevelName", customer.DiscountLevelID);
return View(customer);
}

You need to replace
customer.CustomerLogoPath = physicalFullPath;
with
customer.CustomerLogoPath = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~") + "/Images/" + ImageName;
if you want to save virtual path of the image instead of its physical path.

Related

Display image in front end in ASP.NET MVC

In ASP.NET MVC, the image path is stored in the database and server folder (image) but not displayed on the front.
Images are shown like this:
I was trying to display the image on the front in ASP.NET MVC.
I also attached the code of the controller and view to display the image using the Entity Framework model
In my controller method:
[HttpPost]
public ActionResult Create(Personaltable p, Personal u)
{
try
{
// TODO: Add insert logic here
string filename = Path.GetFileNameWithoutExtension(u.AttachPicture.FileName);
string extension = Path.GetExtension(u.AttachPicture.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
u.ImagePath = "~/Image/" + filename;
filename = Path.Combine(Server.MapPath("~/Image/"), filename);
u.AttachPicture.SaveAs(filename);
using (PersonaltableEntities entity = new PersonaltableEntities())
{
var t = new Personaltable()//Make Variable of Table
{
AttachPicture=SaveToPhysicalLocation(u.AttachPicture),
LastPayCertificate = SaveToPhysicalLocation(u.LastPayCertificate)
};
db.Personaltables.Add(t);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch()
{}
}
private string SaveToPhysicalLocation(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
return path;
}
return string.Empty;
}
This is the view Controller on which I only show the image uploaded by the user in a list form.
public ActionResult Index()
{
return View(db.Personaltables.ToList());
}
This is my view:
#foreach (var item in Model)
{
<tr> <td><img src="~/Image/" width="100",height="250"/></td></td>
}
You must write src="~/Image/#item.ImagePath"
#foreach (var item in Model)
{
<tr> <td><img src="~/Image/(????)" width="100",height="250"/></td></td>
}

How to add "upload file button" with my existing form and get the primary key of that previous form in the new table of UploadFile Database?

This is my controller in which the following fields already exist:
[HttpPost]
public ActionResult Save(Rent Rent)
{
if (Rent.Id == 0)
_Context.Rent.Add(Rent);
else
{
var rentInDb = _Context.Rent.Single(c => c.Id == Rent.Id);
rentInDb.tenantId = Rent.tenantId;
rentInDb.unitId = Rent.unitId;
rentInDb.startDate = Rent.startDate;
rentInDb.endDate = Rent.endDate;
rentInDb.Amount = Rent.Amount;
rentInDb.leaseStatus = Rent.leaseStatus;
}
_Context.SaveChanges();
return RedirectToAction("leaseStatus", "Home");
}
I have already created uploadFile table in which I can get it's path on uploading but I want the previous controller ID to merge with each upload of file and want the previous form Id in the new database of UploadFile which I have created!
PS: I have added previous form Id in uploadFile table using code first.
I need the code for my controller
okay so basically I wanted my form to look like this :
I wanted the existing fields like tenantId , UnitId , StartDate ,etc from my previous database and then I created a new database for file Upload and made my form look like this !!
The query was how to get the ID of my old database into the new database of "FileUpload" .
so this is how my controller and Action looks like :
[HttpPost]
public ActionResult Save(Rent Rent , FileUpload upload, HttpPostedFileBase file)
{
if (Rent.Id == 0)
_Context.Rent.Add(Rent);
else
{
var rentInDb = _Context.Rent.Single(c => c.Id == Rent.Id);
rentInDb.tenantId = Rent.tenantId;
rentInDb.unitId = Rent.unitId;
rentInDb.startDate = Rent.startDate;
rentInDb.endDate = Rent.endDate;
rentInDb.Amount = Rent.Amount;
rentInDb.leaseStatus = Rent.leaseStatus;
}
_Context.SaveChanges();
var rent = _Context.Rent.Single(r => r.Id == Rent.Id);
var up = Request.Files["file"];
if (up.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var guid = Guid.NewGuid().ToString();
var path = Path.Combine(Server.MapPath("~/uploads"), guid + fileName);
file.SaveAs(path);
string fl = path.Substring(path.LastIndexOf("\\"));
string[] split = fl.Split('\\');
string newpath = split[1];
string imagepath = "~/uploads/" + newpath;
upload.length = imagepath;
upload.Rent = rent;
_Context.FileUpload.Add(upload);
_Context.SaveChanges();
}
return RedirectToAction("leaseStatus", "Home");
}
In this POST method the existing form of old database is getting added with the help of _Context.SaveChanges();
and after that the ID Which I got from existing fields got saved in the new variable I created Just after _Context.SaveChanges();
and called that value in fileUpload code .
And Finally this is how I got my Id of old database of existing form into new Table of fileUpload !!

How to display uploaded image in asp .net application?

I uploaded an image to server using form fileData:
[Route("upload")]
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
try
{
if (!Request.Content.IsMimeMultipartContent()) {
Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
var provider = GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);
//Get Album name from Form
var titleOfAlbum = GetTitleOfAlbum(provider);
//get path to file
var pathToCoverDecoded = result.FileData.First().LocalFileName;
//Encodeing to base 64 path
var bytes = Encoding.UTF8.GetBytes(pathToCoverDecoded);
var base64 = Convert.ToBase64String(bytes);
Album al = new Album();
al.Title = titleOfAlbum;
al.PathToCover = base64;
db.Albums.Add(al);
db.SaveChanges();
return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
private string GetDesereleazedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
private string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
private MultipartFormDataStreamProvider GetMultipartProvider()
{
var uploadFolder = HttpContext.Current.Server.MapPath("~/Files");
if (Directory.Exists(uploadFolder) == false)
{
Directory.CreateDirectory(uploadFolder);
}
return new MultipartFormDataStreamProvider(uploadFolder);
}
private string GetTitleOfAlbum(MultipartFormDataStreamProvider provider)
{
var titleOfAlbum = "";
foreach(var key in provider.FormData.GetValues(0))
{
titleOfAlbum = key;
}
return titleOfAlbum;
}
}
Path looks like:
"C:\Users\Oops\Documents\Visual Studio 2015\Projects\WebApplication1\ForMyCustomers\WebApplication1\Files\BodyPart_b40d80c5-47dc-41db-8e35-9d39d4e27939"
I getting path from FileData:
and convert it to base64, but it doesn't displays at page
I've got File not found error.
How can I resolve it? if the URL is wrong how can I get correct one?
You cannot use physical path (the one you used) on web. The physical path like "C:\something" is the path that can be used only by your OS.
The URL however, is the path that you need and to use and to do that you need to put your files somewhere that is readable by your host (IIS).
You are already writing your files in "~/Files". so you just need to add the file name at the end.
var url= "~/Files/"+filename;
you need to save the file name when you are uploading your file so when you want to fetch data from DB, fetch the file name from DB and create the url using that.

Update records using Entity Framework and ASP.NET MVC5

I am using following function to edit the employee records.
public async Task<ActionResult> Edit([Bind(Include = "Id,EmployeeId,Name,FatherName,JoiningDate,EndDate,InitialSalary,CurrentSalary,CurrentAddress,PermanentAddress,ContactNumber,EmailId,Gender,DOB,DeptId,DigId,PFNo,BranchCode,Qualification")] Employee employee)
{
if (ModelState.IsValid)
{
string fileName = null;
if (Request.Files["ImageFileToUpload"]!=null)
{
///Saving the file to EmployeeImages folder with unique name.
HttpPostedFileBase file = Request.Files["ImageFileToUpload"];
fileName = UploadEmployeeImage(file);
}
else
{
///what condition I need to write here so that if no image selected then it will not update the image field?
///if I am writing
fileName = db.Employees.Find(employee.Id).PhotoPath;
///it’s showing error.
}
employee.PhotoPath = fileName;
db.Entry(employee).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.DeptId = new SelectList(db.Departments, "DeptId", "DeptName", employee.DeptId);
ViewBag.DigId = new SelectList(db.Designations, "DegId", "DegName", employee.DigId);
ViewBag.BranchCode = new SelectList(db.Branches, "BranchId", "BranchName", employee.BranchCode);
return View(employee);
}
I want to update the image field when I select image otherwise the employee image should not be changed but other records may change.
Please suggest what I need to update in my code.
Finally i got the solution of my question. Following code i used to solve my problem.
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("Edit")]
public async Task<ActionResult> Edit_Post(int Id)
{
Employee employee = new Employee();
employee = db.Employees.FindAsync(Id).Result;
//if (ModelState.IsValid)
//{
string fileName = null;
if (Request.Files["ImageFileToUpload"].ContentLength >0)
{
var file = Request.Files["ImageFileToUpload"];
///Saving the file to EmployeeImages folder with unique name.
if (!string.IsNullOrEmpty(employee.PhotoPath))
{
DeleteEmployeeImage(employee.PhotoPath);
}
fileName = UploadEmployeeImage(file);
TryUpdateModel(employee);
employee.PhotoPath = fileName;
}
else
{
TryUpdateModel(employee, null, null, new string[] { "PhotoPath" });
}
if (employee.DigId <= 0)
{
ModelState.AddModelError("DigId", "Designation is required");
}
if (ModelState.IsValid)
{
db.Entry(employee).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.DeptIdList = new SelectList(db.Departments, "DeptId", "DeptName", employee.DeptId);
ViewBag.DigIdList = new SelectList(db.Designations, "DegId", "DegName", employee.DigId);
ViewBag.BranchCodeList = new SelectList(db.Branches, "BranchId", "BranchName", employee.BranchCode);
return View(employee);
}
You can set the path when you have selected an image.
if (Request.Files["ImageFileToUpload"]!=null)
{
///Saving the file to EmployeeImages folder with unique name.
HttpPostedFileBase file = Request.Files["ImageFileToUpload"];
fileName = UploadEmployeeImage(file);
employee.PhotoPath = !string.isNullOrWhiteSpace(fileName) ? fileName : employee.PhotoPath ;
}
//else
//{
// else part not required.
//}
db.Entry(employee).State = EntityState.Modified;
await db.SaveChangesAsync();

Using MVC Controller to replace .ashx

I need a controller to handle file uploads. Is it possible to just have a handler print text directly to the page rather than return view(); ?
public ActionResult Upload(HttpContext context)
{
HttpPostedFile file = context.Request.Files["fileData"];
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
string userID = userGuid.ToString();
string targetLocation = "D:\\inetpub\\wwwroot\\RTDOTNETMEMBER\\audio\\songs\\mp3\\" + userID + "\\" + file.FileName;
file.SaveAs(targetLocation);
Response.Write("Testing");
}
Perhaps using ContentResult will do the job:
return new ContentResult() {
Content = "Testing",
ContentEncoding = System.Text.Encoding.UTF32,
ContentType = "text/plain"
};
Just change the return type of your action method to string and return a string. It would look somethig like this:
public string ReturnString()
{
return "Just a string";
}

Categories

Resources