I have issue in uploading images path into database and moving imagesg into folder, here is code:
public ActionResult UploadImages(
HttpPostedFileBase formFilled,
HttpPostedFileBase sixPics,
HttpPostedFileBase buyerCNIC,
HttpPostedFileBase sellerCNIC
)
{
if (Session["user"] == null)
{
return RedirectToAction("Login", "User");
}
CustomerDocumentImages dbCustomerDocs = new CustomerDocumentImages();
string recieverName = Request.Form["RecieverName"];
var allowedExtensions = new[] {
".Jpg", ".png", ".jpg", "jpeg"
};
dbCustomerDocs.FormFilledPhysicalPath = formFilled.ToString();
var _formFilled = Path.GetFileName(formFilled.FileName); //getting only file name(a.jpg)
var ext = Path.GetExtension(formFilled.FileName);
if (allowedExtensions.Contains(ext))
{
string name = Path.GetFileNameWithoutExtension(_formFilled); //getting file name without extension
string formImage = name + "_" + DateTime.Now + ext; //appending the name with id
// store the file inside ~/project folder(Img)
var path = Path.Combine(Server.MapPath("~/Images"), formImage);
dbCustomerDocs.FormFilledPhysicalPath = path;
dbCustomerDocs.FormFilled = _formFilled;
dbCustomerDocs.RecieverName = recieverName;
try
{
var currentAllotmentId = Convert.ToInt32(Request.Form["AllotmentId"]);
var dbAllotment = db.Allotments.SingleOrDefault(i => i.AllotmentId == currentAllotmentId);
dbCustomerDocs.AllotmentId = dbAllotment.AllotmentId;
dbAllotment.IsCustomerDocsUploaded = true;
}
catch (Exception)
{
ModelState.AddModelError("", "Please select valid allotment");
}
db.CustomerDocumentImagess.Add(dbCustomerDocs);
db.SaveChanges();
formFilled.SaveAs("~Images"+path);
return RedirectToAction("Index");
}
else
{
ViewBag.message = "Please choose only Image file";
}
return View();
}
I have also used server.mappath but it woking fine on localhost but giving error on windows live server( on save as method ) , in case of combine.mappath works fine but not moving image into folder. please guide me, thanks in advance.
Related
I am just trying to learn ASP.NET MVC and am having an issue, well not so much of an issue but lack of understanding any is not working I am trying to update an SQL table, the code below works fine if I want to delete a table but all I want to do is to add another file to the data table
public async Task<IActionResult> DeleteSnTFileFromFileSystem(int id)
{
var file = await context.SnTModels.Where(x => x.Id == id).FirstOrDefaultAsync();
if (file == null)
return null;
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + file.FilePath);
if (System.IO.File.Exists(basePath))
{
System.IO.File.Delete(basePath);
}
context.SnTModels.Remove(file);
context.SaveChanges();
TempData["Message"] = $"Removed {file.Name + file.Extension} successfully from File System.";
return RedirectToAction("Scenario");
}
Here is my code to create the table
[HttpPost]
public async Task<IActionResult> SnTUploadToFileSystem(List<IFormFile> files, string description)
{
foreach (var file in files)
{
var subPath = "\\*dir file\\";
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + subPath);
bool basePathExists = System.IO.Directory.Exists(basePath);
if (!basePathExists)
Directory.CreateDirectory(basePath);
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var filePath = Path.Combine(basePath, file.FileName);
var extension = Path.GetExtension(file.FileName);
if (!System.IO.File.Exists(filePath))
{
// saving our file to the file system
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
// creating a model and save this model into the db
var SnTModel = new SnTOnFileSystem
{
CreatedOn = DateTime.UtcNow,
FileType = file.ContentType,
Extension = extension,
Name = fileName,
Description = description,
FilePath = subPath + file.FileName
};
context.SnTModels.Add(SnTModel);
context.SaveChanges();
}
}
TempData["Message"] = "File successfully uploaded to File System.";
return RedirectToAction("Index");
}
Here is the post to update the table
[HttpPost]
public async Task<IActionResult> SnTUpdateToFileSystem(List<IFormFile> files, int id)
{
var file = files[0];
var subPath = "\\Training\\SnT\\Document\\";
var basePath = Path.Combine(Directory.GetCurrentDirectory() + "\\wwwroot" + subPath);
bool basePathExists = System.IO.Directory.Exists(basePath);
if (!basePathExists)
Directory.CreateDirectory(basePath);
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var documentFilePath = Path.Combine(basePath, file.FileName);
var extension = Path.GetExtension(file.FileName);
if (!System.IO.File.Exists(documentFilePath))
{
// saving our file to the file system
using (var stream = new FileStream(documentFilePath, FileMode.OpenOrCreate))
{
await file.CopyToAsync(stream);
}
// creating a model and save this model into the db
var SnTModel = new SnTOnFileSystem
{
Name = fileName,
DocumentFilePath = subPath + file.FileName
};
context.SnTModels.Update(SnTModel);
context.SaveChanges();
}
TempData["Message"] = "Document successfully uploaded to File System.";
return RedirectToAction("Scenario");
}
Actually I'm try to upload a file from user. But I'm getting error. I tried various way even the Microsoft doc also. I can't help myself. So please help me
Link: Microsoft Doc dotnet core 3.1
My action :
[HttpPost]
public async Task<IActionResult> Updateperson(UpdatePersonViewModel updatePerson)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if(updatePerson.Photo != null)
{
string[] words = updatePerson.Photo.FileName.Split('.');
int a = words.Rank;
uniqueFileName = words[a];
uniqueFileName = Guid.NewGuid().ToString() + "_." + uniqueFileName;
string filePath = Path.Combine("Images",uniqueFileName);
//string filePath = Path.Combine(config["Images"], uniqueFileName);
// using (var stream = System.IO.File.Create(filePath))
// {
// await formFile.CopyToAsync(stream);
// }
await updatePerson.Photo.CopyToAsync(new FileStream(filePath,FileMode.Create));
}
_context.Persons.Update(updatePerson);
_context.SaveChanges();
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
else
{
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
}
>>> config is a object of IConfiguration
Here is Error:
It means no such directory named Image exists!
You can simply check if it exists, or create one if it doesn't exist.
if(!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
To test:
Use a directoryPath variable like this:
var directoryPath=Path.Combine(Directory.GetCurrentDirectory(), "Images");
I have an existing web site that allows the user (normally me) to upload pictures and then to display the image on the appropriate page. I am now trying to add this functionality to a new web site.
In visual studio I opened the new web site and did an ‘add existing item’ to copy the model/view/controller from the old web site. Made a few changes to remove unneeded functionality from the code and a few other minor things.
In both I store the image in a folder named /data/Images. When I execute the code for the new site (Lat34North) and add an image, the image gets added, and the everything appears to work (no errors).
Problem:
If I look at the folder (new solution) using “File Explorer”, the jpg appears, in this case, on my hard drive and in the correct folder.
If I try and access the folder (~/Data/Images) via Visual Studio, the jpg does not show up.
When I try and display the image from the web site, I just get that funny little icon you get when the image is not found.
Photo Controller
//
[Authorize]
public ActionResult PhotoCreate(string CallingState, string masterMarkerID, string markerTitle)
{
ViewBag.photoCallingState = CallingState;
ViewBag.photoMarkerID = masterMarkerID;
ViewBag.photomarkerTitle = markerTitle;
return View();
}
//
// POST: /Photo/Create
[AcceptVerbs(HttpVerbs.Post)]
[Authorize]
public ActionResult PhotoCreate(Photo photo, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
photo.PhotoLinkRecID = photo.savePhotoState + photo.saveMarkerID;
if (photo.PhotoSequence == 0)
{
var no_Photo = from s in db.Photo
where s.PhotoLinkRecID == photo.PhotoLinkRecID
select s;
int noPhoto = no_Photo.Count();
int Sequence = (noPhoto * 20);
photo.PhotoSequence = Sequence;
}
photo.PhotoDateCreated = DateTime.Now;
photo.PhotoCreatedBy = #User.Identity.Name;
if (photo.fileUpload != null && photo.fileUpload.ContentLength > 0)
{
// get the file extension
photo.PhotoLinkRecID = photo.savePhotoState + photo.saveMarkerID; // Create key to link photo to the approiate marker -- // unique record identifier
photo.PhotoState = photo.savePhotoState;
photo.PhotoMarkerID = photo.saveMarkerID;
var fileName = Path.GetFileName(photo.fileUpload.FileName);
var FileExtension = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
photo.PhotoFileType = FileExtension;
db.Photo.Add(photo); // add new photo record to the DB
db.SaveChanges();
photo.PhotoRecID = "Photo" + photo.PhotoID.ToString(); // unique record identifier
var saveFile = photo.savePhotoState + photo.PhotoRecID + "." + photo.PhotoFileType; // new file name
var path = Path.Combine(Server.MapPath("~/Data/Images"), saveFile); // save the file
HttpPostedFileBase hpf = photo.fileUpload as HttpPostedFileBase;
hpf.SaveAs(path);
Image image = Image.FromFile(path);
photo.PhotoHeight = image.Height;
photo.PhotoWidth = image.Width;
try
{
//get the date taken from the files metadata
PropertyItem pi = image.GetPropertyItem(0x9003);
string sdate = Encoding.UTF8.GetString(pi.Value).Replace("\0", String.Empty).Trim();
string secondhalf = sdate.Substring(sdate.IndexOf(" "), (sdate.Length - sdate.IndexOf(" ")));
string firsthalf = sdate.Substring(0, 10);
firsthalf = firsthalf.Replace(":", "/");
sdate = firsthalf + secondhalf;
photo.PhotoDateTaken = sdate;
}
catch { }
try
{
double? lat = ImageExtensions.GetLatitude(image);
double? lon = ImageExtensions.GetLongitude(image);
if (lat > 1)
{
photo.PhotoLatDirection = "N";
string latString = lat.ToString();
//photo.PhotoLat = latString.Substring(0, 10);
if (latString.Length < 10)
{
photo.PhotoLat = latString;
}
else
{
photo.PhotoLat = latString.Substring(0, 10);
}
//photo.PhotoLat = lat.ToString();
photo.PhotoLongDirection = "W";
string longString = lon.ToString();
if (longString.Length < 10)
{
photo.PhotoLong = longString;
}
else
{
photo.PhotoLong = longString.Substring(0, 10);
}
//photo.PhotoLong = lon.ToString();
}
}
catch { }
}
db.SaveChanges();
return RedirectToAction("PhotoEdit", new { id=photo.PhotoID });
}
return View(photo);
The old web site uses EntityFramework, Version=5.0.0.0
The new web site uses EntityFramework, Version=6.0.0.0
The other difference between the two are the packages I have installed. Could I be missing one?
THIS IS MY FILE UPLOAD AND DOWNLOAD CODE
[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");
}
public ActionResult Downloads(int id)
{
var fl = _Context.FileUpload.Where(f => f.rentId == id);
var up = Request.Files["file"];
return View(fl );
}
public FileResult Download(string ImageName)
{
var FileVirtualPath = "~/uploads/" + ImageName;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
THIS IS MY VIEW !!
#model IEnumerable<mallform.Models.FileUpload>
#{
ViewBag.Title = "Downloads";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Downloads</h2>
#foreach (var file in Model)
{
Download
}
THIS SHOWS STANDARD 404.0 AND SOMETIME hidden element error :( Please help. In my code it includes the upload a file code,
then there Is a download action which leads me to download view and In download view, I have a link to download the file by file result. But It always shows me an error. Please tell me if there is an issue with the path or what is going on?
Error Code 404 means the url is not found by your anchor tag. https://en.wikipedia.org/wiki/HTTP_404
You need to pass ImageName parameter from your anchor tag to the controller. You can do something like this:
View
#model IEnumerable<mallform.Models.FileUpload>
#{
ViewBag.Title = "Downloads";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Downloads</h2>
#foreach (var file in Model)
{
#Html.ActionLink(
"Download File", // Anchor Text
"Download", // Action Name
"Controller Name", // Controller Name
new {
ImageName= "Pass the value of imagename parameter"
},
null // Html Attributes
)
}
Controller
public FileResult Download(string ImageName)
{
//var FileVirtualPath = "~/uploads/" + ImageName;
//If using Physical Path
//var FileVirtualPath = HttpContext.Current.Request.MapPath("~/uploads/" + ImageName);
//If using Virtual Path
var FileVirtualPath = HttpContext.Current.Server.MapPath("~/uploads/" + ImageName);
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
File Result Action should be like this.
public FileResult Download(string ImageName)
{
byte[] fileBytes = System.IO.File.ReadAllBytes(Server.MapPath(#"~/uploads/"+ImageName));
string fileName = "myfile."+Path.GetExtension(Server.MapPath(#"~/uploads/"+ImageName));
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
I have an application that uploads images, I am trying to get the path to store on the server and not on my C:drive. Below is the code in the controller:
if (ModelState.IsValid)
{
if (file != null)
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Images/");
try
{
if (!Directory.Exists(physicalPath))
Directory.CreateDirectory(physicalPath);
string physicalFullPath = Path.Combine(physicalPath, ImageName);
file.SaveAs(physicalFullPath);
customer.CustomerLogo = ImageName;
customer.CustomerLogoPath = physicalFullPath;
db.Customers.Add(customer);
db.SaveChanges();
}
catch(Exception e)
{
return View("Error",e.Message );
}
}
return RedirectToAction("Index");
}
return View(customer);
}
It's currently being stored like this(See above Image) I need the path to be "admin.loyaltyworx.co.za\Images\jeep.jpg" How can I achieve this?
Use
string physicalPath = "c:\\admin.loyaltyworx.co.za\\Images";
Instead of
string physicalPath = Server.MapPath("~/Images/");