Cannot upload file from form .NET - c#

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

Related

Best way to return zip file built on the fly using ASP.NET MVC action without delay

I'm creating zip archive using selected file pattern and need to have a fast method that can return it async when it is being built.
public async Task<FileStreamResult> DownloadStudy(long studyId, string Pattern= "*_70_0_70_0.dcm")
{
var FilePaths = System.IO.Directory.EnumerateFiles(studyDir, Pattern, SearchOption.AllDirectories);
var dir = new DirectoryInfo(studyDir);
var fName = dir.Name + ".zip";
var zipPath = Path.Combine(dir.Parent.FullName, fName);
var zipFileMemoryStream = new FileStream(zipPath,FileMode.Create);
using (ZipArchive archive = new ZipArchive(zipFileMemoryStream, ZipArchiveMode.Update, leaveOpen: true))
{
foreach (var filePath in FilePaths)
{
var filename = Path.GetFileName(filePath);
var pdir = Path.GetFileName(Path.GetDirectoryName(filePath));
archive.CreateEntryFromFile(filePath, pdir + "/" + filename);
}
}
zipFileMemoryStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(zipFileMemoryStream, "application/octet-stream") { FileDownloadName = studyId.ToString() + ".zip" };
}
Is there a better way to have the download starts once the action is called and while the zip archive is being built?

Saving And fetching images MongoDB

i have created method that create a User which in following i want it to create user Profile with it.
here is my code:
public Task CreateUser(User user, IFormFile image)
{
if (image is not null && image.Length > 0)
{
string uploads = Path.Combine(#"./", "Uploads");
Directory.CreateDirectory(uploads);
if (image.Length > 0)
{
var filename = Guid.NewGuid().ToString() + image.FileName;
string filePath = Path.Combine(uploads, filename);
using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
image.CopyTo(fileStream);
}
user.Image = filename;
}
}
else
{
user.Image = "";
}
return _user.InsertOneAsync(user);
}
but then when i want to create user in UI
#inject IUserData Userdata
await Userdata.CreateUser(user);
i got an error under createuser and it says i should pass the image parameter which when i pass it again gives me another error
can you please help me with saving this image?
thanks

ASP.NET converting .doc to .pdf relative pathing mapping fail

Whenver I upload a file I want to have it automatically converted into
.pdf (I am doing that using NuGet). The thing is the upload scheme is done using
relative pathing. I do now know what to put into this parantheses:
var wordDocument = appWord.Documents.Open(uploadedFile);
This gives a null exception; saying that the file has NOT been found.
NOTE that the uploading code , without the conversion part, is working flawlessly.
What should I replace uploadedFile with in order to work? I will leave my
realtive path mapping code below so you can see everything that I have done
in order to better help you (and me as well) with what should be put into
that parantheses in order to work? Thank you so much!
public IActionResult Index1()
{
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
[HttpPost]
public IActionResult Index1(IFormFile[] files)
{
// Iterate each files
foreach (var file in files)
{
// Get the file name from the browser
var fileName = System.IO.Path.GetFileName(file.FileName);
// Get file path to be uploaded
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);
// Check If file with same name exists and delete it
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
// Create a new local file and copy contents of uploaded file
using (var localFile = System.IO.File.OpenWrite(filePath))
using (var uploadedFile = file.OpenReadStream())
{
var appWord = new Application();
if (appWord.Documents != null)
{
//yourDoc is your word document
var wordDocument = appWord.Documents.Open(file) ;
string pdfDocName = "pdfDocument.pdf";
if (wordDocument != null)
{
wordDocument.ExportAsFixedFormat(pdfDocName,
WdExportFormat.wdExportFormatPDF);
wordDocument.Close();
}
appWord.Quit();
}
uploadedFile.CopyTo(localFile);
}
}
ViewBag.Message = "Files are successfully uploaded";
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename is not availble");
var path = Path.Combine(Directory.GetCurrentDirectory(), "upload", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".csv", "text/csv"}
};
}```
//Get the path of existing Word document
string fullpath = #"...\..\DocToPDF.docx";
//Loads an existing Word document
WordDocument wordDocument = new WordDocument(fullpath, FormatType.Docx);
//Creates an instance of the DocToPDFConverter
DocToPDFConverter converter = new DocToPDFConverter();
//Converts Word document into PDF document
PdfDocument pdfDocument = converter.ConvertToPDF(wordDocument);
//Releases all resources used by DocToPDFConverter
converter.Dispose();
//Closes the instance of document objects
wordDocument.Close();
//Saves the PDF file
pdfDocument.Save("DocToPDF.pdf");
//Closes the instance of document objects
pdfDocument.Close(true);```
this is the NuGet documentation they had on the site, I have got problems at the 2nd row : on specifying the full path

How to save Images to different folders in database using ASP.NET Core?

I have an ASP.NET MVC project that is working fine to save images to different folders and sub folders. But when I want to do similarly in ASP.NET Core 2.2, it is not working as it is and I need help to solve this problem and I would appreciate your help very much.
Here is my ASP.NET MVC version that not working in ASP.NET Core 2.2:
public ActionResult AddCar(CarVM model, HttpPostedFileBase file)
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
Car c = new Car();
c.Name = model.Name;
c.Mileage = model.MileAge;
db.Car.Add(c);
db.SaveChanges();
// Get Inserted Id;
int id = c.CarId;
}
// to insert Image of the car in different folders in ASP.NET MVC I do like this, but this not working in ASP.NET Core 2.2
// Create necessary directories
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(#"\")));
// I add folder "CarsImage" because I have other Products image too
var pathString1 = Path.Combine(originalDirectory.ToString(), "CarsImage");
var pathString2 = Path.Combine(originalDirectory.ToString(), "CarsImage\\" + id.ToString());
var pathString3 = Path.Combine(originalDirectory.ToString(), "CarsImage\\" + id.ToString() + "\\Thumbs");
var pathString4 = Path.Combine(originalDirectory.ToString(), "CarsImage\\" + id.ToString() + "\\Gallery");
var pathString5 = Path.Combine(originalDirectory.ToString(), "CarsImage\\" + id.ToString() + "\\Gallery\\Thumbs");
// Check if directory exist, if not then create them
if (!Directory.Exists(pathString1))
Directory.CreateDirectory(pathString1);
if (!Directory.Exists(pathString2))
Directory.CreateDirectory(pathString2);
if (!Directory.Exists(pathString3))
Directory.CreateDirectory(pathString3);
if (!Directory.Exists(pathString4))
Directory.CreateDirectory(pathString4);
if (!Directory.Exists(pathString5))
Directory.CreateDirectory(pathString5);
// Check if file was uploaded
if (file != null && file.ContentLength > 0)
{
// Get file extension
string ext = file.ContentType.ToLower();
// Verify extension
if (ext != "image/jpg" &&
ext != "image/jpeg" &&
ext != "image/pjpeg" &&
ext != "image/gif" &&
ext != "image/x-png" &&
ext != "image/png")
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
model.Categories = new SelectList(db.Category.ToList(), "CategoryId", "CategoryName");
model.Mileages = new SelectList(db.MileAge.ToList(), "MileAgeId", "Mile");
ModelState.AddModelError("", "The image was not uploaded - Wrong image extension");
return View(model);
}
}
// Init image name
string imageName = file.FileName;
// Save image name to Car table
using (ApplicationDbContext db = new ApplicationDbContext())
{
Car dto = db.Car.Find(id);
dto.ImageName = imageName;
db.SaveChanges();
}
// Set Original and image paths
var path = string.Format("{0}\\{1}", pathString2, imageName);
var path2 = string.Format("{0}\\{1}", pathString3, imageName);
// Save Original
file.SaveAs(path); // Not working in core
// Create and save thumb
WebImage img = new WebImage(file.InputStream); // WebImage not working in core
img.Resize(200, 200);
img.Save(path2);
}
}
So I have tried with IFormFile.... and
string uploadFolder = Path.Combine(hostingEnvirnment.WebRootPath, "images\\upload");
But I don't how to do. Please help!
In ASP.NET Core , you could use Directory.GetCurrentDirectory() to get the current working directory of the application and combine the folder path under the static file root directory .
var originalDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\Images\\Uploads");
Then use Path.Combine() to set the original and image paths , and you could save the files of type IFormFile like below :
// Set Original and image paths
var filePath = Path.Combine(pathString2, imageName);
var filePath2 = Path.Combine(pathString3, imageName);
// Save Original
file.CopyTo(new FileStream(filePath, FileMode.Create));
For saving the thumbnail image , you could Installed System.Drawing.Common package and use the below code :
Stream stream = file.OpenReadStream();
Image newImage = GetReducedImage(200, 200, stream);
newImage.Save(filePath2);
public Image GetReducedImage(int width, int height, Stream resourceImage)
{
try
{
Image image = Image.FromStream(resourceImage);
Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero);
return thumb;
}
catch (Exception e)
{
return null;
}
}
The complete code is as follows:
public readonly ApplicationDbContext _context;
public HomeController( ApplicationDbContext context)
{
_context = context;
}
[HttpPost]
public ActionResult AddCar(Car model, IFormFile file)
{
Car c = new Car();
c.Name = model.Name;
c.Mileage = model.MileAge;
_context.Car.Add(c);
_context.SaveChanges();
// Get Inserted Id;
int id = c.CarId;
// Create necessary directories
var originalDirectory = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\Images\\Uploads");
// different image folder
var pathString1 = Path.Combine(originalDirectory.ToString(), "CarsImage");
var pathString2 = Path.Combine(originalDirectory.ToString(), "CarsImage\\" + id.ToString());
var pathString3 = Path.Combine(originalDirectory.ToString(), "CarsImage\\" + id.ToString() + "\\Thumbs");
var pathString4 = Path.Combine(originalDirectory.ToString(), "CarsImage\\" + id.ToString() + "\\Gallery");
// Check if directory exist, if not then create them
if (!Directory.Exists(pathString1))
Directory.CreateDirectory(pathString1);
if (!Directory.Exists(pathString2))
Directory.CreateDirectory(pathString2);
if (!Directory.Exists(pathString3))
Directory.CreateDirectory(pathString3);
if (!Directory.Exists(pathString4))
Directory.CreateDirectory(pathString4);
// Check if file was uploaded
if (file != null && file.Length > 0)
{
// Get file extension
string ext = file.ContentType.ToLower();
// Verify extension
if (ext != "image/jpg" &&
ext != "image/jpeg" &&
ext != "image/pjpeg" &&
ext != "image/gif" &&
ext != "image/x-png" &&
ext != "image/png")
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
model.Categories = new SelectList(db.Category.ToList(), "CategoryId", "CategoryName");
model.Mileages = new SelectList(db.MileAge.ToList(), "MileAgeId", "Mile");
ModelState.AddModelError("", "The image was not uploaded - Wrong image extension");
return View();
}
}
// Init image name
string imageName = file.FileName;
// Save image name to Car table
Car dto = _context.Car.Find(id);
dto.ImageName = imageName;
_context.SaveChanges();
// Set Original and image paths
var filePath = Path.Combine(pathString2, imageName);
var filePath2 = Path.Combine(pathString3, imageName);
// Save Original
file.CopyTo(new FileStream(filePath, FileMode.Create));
// Create and save thumb
Stream stream = file.OpenReadStream();
Image newImage = GetReducedImage(200, 200, stream);
newImage.Save(filePath2);
}
return View();
}
public Image GetReducedImage(int width, int height, Stream resourceImage)
{
try
{
Image image = Image.FromStream(resourceImage);
Image thumb = image.GetThumbnailImage(width, height, () => false, IntPtr.Zero);
return thumb;
}
catch (Exception e)
{
return null;
}
}
You need to use IHostingEnvironment to get the application path in ASP.NET Core. Check this SO answer for more details.

How to pass ID to image file name using MVC?

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");
}

Categories