Display image in front end in ASP.NET MVC - c#

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

Related

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 !!

ASP.NET MVC List of attachments (from binary data)

Using ASP.NET MVC and SQL Server 2016. I have attachments which stored as binary data in SQL Server.
Table with data looks like:
attachment_ID | attachment_GUID | attachment_data | attachment_name|
--------------|------------------|-----------------|----------------|
211 | A893C2Z1-4C0 | 0x255044462... | file1.doc |
212 | A893C2R5-4F0 | 0x255044455... | file5.pdf |
I need to display list of this attachments (names), as hyperlinks in html page. So if I click on attachment name it should start the downloading process.
Need help with an ASP.NET MVC controller.
I have controller which downloads a file directly:
using System;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
namespace Project.SERVER.Controllers
{
public class AttachmenttoHTMLController : Controller
{
#region View attachments
[HttpGet]
public ActionResult Get()
{
SqlConnection connection = Project.SERVER.Classes.INT_DataBase.getConnection();
SqlCommand command = new SqlCommand("SELECT * FROM AllAttachments WHERE document_GUID='F3A2AC32-D98D'", connection);
command.Dispose();
SqlDataAdapter sqlDtAdptr = new SqlDataAdapter(command);
System.Data.DataTable result = new System.Data.DataTable();
result.Dispose();
sqlDtAdptr.Fill(result);
sqlDtAdptr.Dispose();
connection.Dispose();
connection.Close();
if (result.Rows.Count > 0 && !System.Convert.IsDBNull(result.Rows[0]["attachment_data"]))
{
byte[] file = (byte[])result.Rows[0]["attachment_data"];
Response.ContentType = result.Rows[0]["attachment_contentType"].ToString();
return File(file, Response.ContentType, result.Rows[0]["attachment_fileName"].ToString());
}
else return new EmptyResult();
}
#endregion
}
}
What should I add to the code to achieve controller for attachment list with option to download when clicked?
You have to save first the binary data into Image Format into your directory project.
Use FileResult
HTML:
<div>
#Html.ActionLink("Download", "Download", "Home");
</div>
HomeController:
public FileResult Download()
{
String path = HostingEnvironment.ApplicationPhysicalPath + "Image\\Capture.PNG";
string fname= Path.GetFileName(path);
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
string fileName = fname;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
Assuming that you have a list in your model
List<Attachment> lst = new List<Attachment>();
This list is the content of your data from your Database and saved the byte to imageformat into you project folder.
Your code from above should fall in here saved the byte with a filename even id.PNG or any. Adding lst.id and lst.filename for html purpose.
public class Attachment
{
public int id { get; set; }
public string filename { get; set; }
}
Your HTML looks like:
<table>
#{
if (Models.GetAttachment.lst.Count > 0)
{
for (int m = 0; m < Models.GetAttachment.lst.Count; m++)
{
<tr>
<td>
#Html.ActionLink("Download", "Download", new { id = Models.GetAttachment.lst.Coun[m].id })
</td>
</tr>
}
}
}
</table>
HomeController With id:
public FileResult Download(int?id)
{
String path = HostingEnvironment.ApplicationPhysicalPath + "Image\\Capture.PNG";
string fname= Path.GetFileName(path);
byte[] fileBytes = System.IO.File.ReadAllBytes(path);
string fileName = fname;
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
the purpose of id to locate the file in your project directory for every user click.

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

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.

Moving information from a controller to a view

I need to move data read from a database from a controller to a view and display it to a table. I can read from the database a store information to an object successfully, but I'm getting a #foreach (var item in Model) error when I run the page. Here is the method that reads the database:
public class DatabaseRead
{
public static async Task MongoReader(string path)
{
{
MongoClient client = new MongoClient();
var db = client.GetDatabase("POWA");
var collection = db.GetCollection<files>("Imported");
var filter = Builders<files>.Filter.Eq("quote_number", path);
var result = await collection.Find(filter).ToListAsync();
foreach (var results in result)
{
ContentDisplay read = new ContentDisplay();
read.product_name = results.product_name;
read.catalog_number = results.catalog_number;
}
}
}
}
and here is my view:
#model List<ProductionOrderWebApp.Controllers.ContentDisplay>
#{ ViewBag.Title = "Display"; }
<h2>Order Table>
<table board="1", style ="width:auto">
<tr>
<th>Item Name</th>
<th>Catalog Number</th>
</tr>
#foreach (var item in Model)
{
<tr>
<th>#Html.Display(item.product_name);</th>
</tr>
}
How can I get the table to display all the entries of the object without getting the error?
EDIT
Here is the code for my controller. All it does is call two methods, one to read a CSV file and write to mongo, and one that reads from the database and attempts to display the contents.
namespace ProductionOrderWebApp.Controllers
pubic class Homecontroller : Controller
{
public ActionResult Index
{
return View();
}
public ActionResult Display()
{
return View();
}
[HttpPost]
public async Task<ActionResult> Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(("C:\\Dev\\ProductionOrderWebApp\\Uploads"), fileName);
file.SaveAs(path);
await CSVRead.CSVReader(path); //calls a method that reads and takes apart a CSV file
await DatabaseRead.MongoReader(path);
}
return View("Display");
}
}
}
Why are you creating a new object of ContentDisplay everytime in the loop, Because of it, you are not passing the required data to the view,
{
ContentDisplay read = new ContentDisplay();
read.product_name = results.product_name;
read.catalog_number = results.catalog_number;
}
First, DatabaseRead.MongoReader needs to return a Task<List<ContentDisplay>> instead of nothing. In that method, you need to declare your return list outside the foreach loop and add to it in there and return like
var returnList = new List<ContentDisplay>();
foreach (var results in result)
{
var read = new ContentDisplay();
read.product_name = results.product_name;
read.catalog_number = results.catalog_number;
returnList.add(read);
}
return returnList;
Then instead of
await DatabaseRead.MongoReader(path);
you need to actually catch it to use
var model = await DatabaseRead.MongoReader(path);
and then pass it along to the view
return View("Display", model);
CAVEATS
I've not done a lot of async await stuff, so there might be something screwy with returning lists.
I'm concerned that await CSVRead.CSVReader(path); is probably also doing nothing while you expect it to do something.
EDIT
public async Task<ActionResult> Index(HttpPostedFileBase file)
{
List<ContentDisplay> model = new List<ContentDisplay>();
if (file != null && file.ContentLength > 0)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var path = System.IO.Path.Combine(("C:\\Dev\\ProductionOrderWebApp\\Uploads"), fileName);
file.SaveAs(path);
await CSVRead.CSVReader(path); //calls a method that reads and takes apart a CSV file
model = await DatabaseRead.MongoReader(path);
}
return View("Display", model);
}

KendoUI: How to get new file name in javascript after renaming uploaded file in controller

I have the following Kendo upload control
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("SaveBackgroundImage", "Plans")
.AutoUpload(true))
.Multiple(false)
.Events(events => events.Success("onSuccess")))
My controller:
public ActionResult SaveBackgroundImage(IEnumerable<HttpPostedFileBase> floorplanFiles, string floorplanId)
{
foreach (var file in files)
{
string fileName = "ABC.jpg" //this will be random
var physicalPath = Path.Combine(Server.MapPath("~/Images/Floorplans/Fullsize"), fileName);
file.SaveAs(physicalPath);
}
// Return an empty string to signify success
return Content("");
}
My javascript:
function onSuccess(e) {
var filename = getFileInfo(e);
alert(filename);
}
function getFileInfo(e) {
return $.map(e.files, function (file) {
var info = file.name;
return info;
}).join(", ");
}
How do I get back "ABC.jpg" as my filename in my javascript instead of the original filename that I select to upload?
Solved by doing this in my controller:
var newImageName = "123.jpg";
return Json(new { ImageName = newImageName }, "text/plain");
and in the onSuccess function:
function onSuccess(e) {
var imageName = e.response.ImageName;
}

Categories

Resources