I want to save my image File using session ID value and then in the uploads folder I want to pass the ID value like 3.jpeg or png
[HttpPost]
public ActionResult AddImage(HttpPostedFileBase postedFile)
{
int compId = Convert.ToInt32(Session["compID"]);
if (postedFile != null)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
postedFile.SaveAs(path + Path.GetFileName(postedFile.FileName));
ViewBag.Message = "File uploaded successfully.";
}
return RedirectToAction("AddCompany");
}
Below i have attached the image
When saving your image, you need to combine the compId and the file extension as follows:
var filename = compId.ToString() + Path.GetExtension(postedFile.FileName);
So your code should look something like this:
[HttpPost]
public ActionResult AddImage(HttpPostedFileBase postedFile)
{
int compId = Convert.ToInt32(Session["compID"]);
if (postedFile != null)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var filename = compId.ToString() + Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(path + filename);
ViewBag.Message = "File uploaded successfully.";
}
return RedirectToAction("AddCompany");
}
Related
I work on ASP.NET Core 2.2 Web API and face an issue: I can't use replace function to change the name property of a selected file that I get when uploaded.
When I try like this:
string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
I get an error
Iform file doesn't contain definition for replace and no accessible extension method Replace accepting first argument of iformfile
Full sample is here:
[HttpPost, DisableRequestSizeLimit]
public IActionResult Upload()
{
try
{
var DisplayFileName = Request.Form.Files[0];
string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
string Month = DateTime.Now.Month.ToString();
string DirectoryCreate = myValue1 + Month;
Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (!Directory.Exists(DirectoryCreate))
{
Directory.CreateDirectory(DirectoryCreate);
}
if (DisplayFileName.Length > 0)
{
var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
var dbPath = Path.Combine(DirectoryCreate, fileName);
using (var stream = new FileStream(dbPath, FileMode.Create))
{
Request.Form.Files[0].CopyTo(stream);
}
return Ok(new { dbPath });
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
How to solve this issue?
sample
suppose i select file developed.xlsx
then after use replace or any way result will be
developed-sddfn78888.xlsx
You can use System.IO.Path to get filename and get file extension from request files.
Change this
string fileName = DisplayFileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
To
string filename = Path.GetFileName(DisplayFileName.FileName);
string fileExtension = Path.GetExtension(DisplayFileName.FileName);
string newFileName = $"{filename}-{Guid.NewGuid().ToString()}{fileExtension}";
Otherwise, you could modify your code to
string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
I'm trying to upload data (image) from form to my .NET App. It saves the Path to the database correctly, but the images are not saved under "wwwroot/images". I will be grateful for your help.
public async Task<IActionResult> Create([Bind("Id,Brand,Model,Description,Price,ImageUrl,CategoryId")] Car car)
{
if (ModelState.IsValid)
{
string webRootPath = _hostEnvironment.WebRootPath;
var files = HttpContext.Request.Form.Files;
if (files.Count > 0)
{
string fileName = Guid.NewGuid().ToString();
var uploads = Path.Combine(webRootPath, "images");
var extenstion = Path.GetExtension(files[0].FileName);
var filePath = Path.Combine(uploads, fileName, extenstion);
car.ImageUrl = "images" + "\\" + fileName + extenstion;
using (var filesStreams = new FileStream(filePath, FileMode.Create))
{
files[0].CopyTo(filesStreams);
}
}
_context.Add(car);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Name", car.CategoryId);
return View(car);
}
Here I add product and save path of image, everything works fine and image path is saved
public ActionResult AddProduct(Product p, HttpPostedFileBase prodImg, decimal[] price)
{
try
{
string absoluthFolderPath = Server.MapPath("\\Images");
string pathOfImage = System.IO.Path.GetExtension(prodImg.FileName);
string newFileName = Guid.NewGuid() + pathOfImage;
absoluthFolderPath += "\\" + newFileName;
prodImg.SaveAs(absoluthFolderPath);
string relitivePath = #"\Images\" + newFileName;
p.ImagePath = relitivePath;
p.Blocked = false;
new ProductsBL().AddProduct(p);
ViewData\["msg"\] = "Successfuly";
}
catch(Exception ex)
{
}
ModelState.Clear();
return View();
}
When trying to update image path it gives me error shown on screenshot
public ActionResult Update(Product modifieDetails, HttpPostedFileBase updImg)
{
string absoluthFolderPath = Server.MapPath("\\Images");
string pathOfImage = System.IO.Path.GetExtension(updImg.FileName);
string newFileName = Guid.NewGuid() + pathOfImage;
absoluthFolderPath += "\\" + newFileName;
updImg.SaveAs(absoluthFolderPath);
string relitivePath = #"\Images\" + newFileName;
modifieDetails.ImagePath = relitivePath;
modifieDetails.Blocked = false;
new ProductsBL().UpdateProduct(modifieDetails);
return RedirectToAction("ListProduct");
}
[1]: http://i.stack.imgur.com/wgE88.png
You need to split this up:
new ProductsBL().AddProduct(p);
In order to save updates to an entity back to the store, you have to set "IsModified" on the entity, and then save the context. Like so...
using (ProductsBL context = new ProductsBL()) {
var p = (some query to get it from the store);
p.ImagePath = relitivePath;
p.Blocked = false;
p.IsModified = true;
context.SaveChanges();
}
As it is, you're creating a new entity and adding that to the store, not updating the existing one.
And, if you're coding in English, please fix the spellings: Modify, Relative, absolute.
I have a kendo ui async file upload with the following options on my view.
<div class="demo-section">
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("Save", "Upload")
.AutoUpload(true)
)
)
</div>
In the corresponding action method ,I would like to set my model's properties for filename .Shown below is what i have currently .
public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
{
// The Name of the Upload component is "files"
if (files != null)
{
foreach (var file in files)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
// The files are not actually saved in this demo
// file.SaveAs(physicalPath);
}
}
// Return an empty string to signify success
return Content("");
}
If there is a way to do it ,please let me know ..
public ActionResult Save(IEnumerable<HttpPostedFileBase> files)
{
var savedFilePaths = new List<string>();
var applicationPath = System.Web.HttpContext.Current.Request.Url.Scheme + "://" + System.Web.HttpContext.Current.Request.Url.Authority + System.Web.HttpContext.Current.Request.ApplicationPath + "/Content/Images/Others/";
// The Name of the Upload component is "files"
if (files != null)
{
foreach (var file in files)
{
// Some browsers send file names with full path.
// We are only interested in the file name.
var fileName = Path.GetFileName(file.FileName);
if (fileName != null)
{
fileName = DateTime.Now.ToString("yyyyMMddmm-") + fileName;
var physicalPath = Path.Combine(Server.MapPath("~/Upload/Hotel"), fileName);
file.SaveAs(physicalPath);
savedFilePaths.Add(applicationPath + fileName);
}
}
}
// Return an empty string to signify success
return Content("");
}
I Make Upload Image In Asp.Net And I Really Save The Image In The Data Base But When i Want To Make A Query To Select The Image It Return The Source Of The Image With No Image Please I Want Any One Know The Solution Please Help Me.`enter code here This Is The Controller Code:
public ActionResult UpLoadImage(HttpPostedFileBase file)
{
if (file != null)
{
UpLoadDBEntities context = new UpLoadDBEntities();
file = Request.Files[0];
string filename = file.FileName;
string contenttype = file.ContentType;
string full = filename + " " + contenttype;
//string path = System.IO.Path.Combine(
// Server.MapPath("~/images/") + file.FileName);
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
Image_table it = new Image_table();
it.Image_Path = filename;
context.Image_table.Add(it);
context.SaveChanges();
}
return View();
}
public JsonResult ShowImage()
{
UpLoadDBEntities context = new UpLoadDBEntities();
Image_table it = new Image_table();
var showimage = (from itbl in context.Image_table
where itbl.ID == 8
select new { itbl.Image_Path });
return Json(showimage , JsonRequestBehavior.AllowGet);
}
You are setting the path as
it.Image_Path = filename;
Yet it gets store on the server as
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
I hope you can see it needs to be it.Image_Path = "~/Images/" + filename;. Also, make sure folks can actually access the path through IIS.