Change file name in asp.net - c#

For my project I'm setting up a page where you can change your profile and upload an image. I've got all of that to work but now I want to make my image unique by matching the file name with the Username (which already is unique)
but I couldn't find a good guide anywhere on google.
Here is my code:
{
if (PfFoto != null)
{
string pic = System.IO.Path.GetFileName(PfFoto.FileName);
string path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), pic);
PfFoto.SaveAs(path);
return RedirectToAction("Index");
}
}
My username is stored in changePF.Name
and the file name is stored in pic
so does anyone know how to do this?

Simply change FileName before SaveAs like :
if (PfFoto != null)
{
string path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), changePF.Name);
PfFoto.SaveAs(path);
return RedirectToAction("Index");
}

If you want your file name to be same as your user name (without the extension part matching), You may use the Path.GetExtension method to get the file extension(ex : .jpg or .png) and concatenate that with your unique username.
if (PfFoto != null)
{
var newFileName = changePF.Name + Path.GetExtension(PfFoto.FileName);
var path = System.IO.Path.Combine(Server.MapPath("/images/PFfotos"), newFileName);
PfFoto.SaveAs(path);
}

Related

Why cant I save a user with picture on Azure, while it works locally?

I have a create method which works fine in localhost. It looks like this:
public PatientViewModel Create(PatientViewModel model)
{
try
{
model.patient!.photoPath = (model.file != null) ? UploadFile(model.file) : "placeholder.png";
model.patient.appUser = appuserAwhole(model);
model.patient.appUser.user = (!model.mode) ? model.user : model.Users!.Where(r => r.userId == model.userid).First();
_idb.patients.Add(model.patient);
idbSaveChanges();
Patientfile pf = new Patientfile();
pf.patientMail = model.patient.emailAddress;
_fdb.patientfiles.Add(pf);
fdbSaveChanges();
}
catch (Exception e) {
System.Diagnostics.Debug.WriteLine(e.Message);
}
return model;
}
This is my UploadFile method:
private string UploadFile(IFormFile photo)
{
string wwwPath = this._env.WebRootPath;
string contentPath = this._env.ContentRootPath;
string path = Path.Combine(wwwPath, "img\\PatientPhotos");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (photo == null)
{
return "default.png";
}
string fileName = Path.GetFileName(photo.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
photo.CopyTo(stream);
}
return fileName;
}
I first get the wwwroot path and use this to save my image. If the image already exist, it uses the image thats already saved (i know this isnt ideal, but it works for me for now).
When I upload a file in localhost and submit, the patient gets saved and so does the image (in wwwroot). On Azure however, the patient and the image dont get saved.
When I dont upload a file, it automatically uses placeholder.png. Now the patient does get saved on Azure, but no image, since none was selected.
Im not getting any errors (probably because its in a production environment), it just returns to the Index page after submitting, without saving anything
In my controller you return to the Index page after creating the patient:
_db.Create(vm);
return RedirectToAction("Index");
Is there any way to fix this problem?

Why is creating a directory not working in my MVC Application?

I'm creating a web application and I allow my users to upload files in one of the forms. I want my method to create a folder when the upload is initiated that has the name of the passed in parameter, in this case, ID.
public ActionResult Async_Save(IEnumerable<HttpPostedFileBase> files, int? id)
{
if (files != null)
{
string filepath = "/Content/CarData/";
Directory.CreateDirectory(filepath + id);
foreach (var file in files)
{
var fileName = Path.GetFileName(file.FileName);
var physicalPath = Path.Combine(Server.MapPath(filepath + id), fileName);
file.SaveAs(physicalPath);
}
}
return Content("");
}
When the user uploads a file, however, an error is thrown:
System.IO.DirectoryNotFoundException: 'Could not find a part of the
path
'C:\GitRepos\MyProject\MyProject\Content\CarData\206\mclaren.jpg'.'
This is accurate because I can see that the directory isn't created. Can anyone assist me with understanding what has gone wrong? I get no errors on the Directory.CreateDirectory(filepath + id); part of the method.

How to get the name of file from uploaded file before save it to local path

I have code like this:
public ActionResult Import(string excel, HttpPostedFileBase excelfile)
{
if (excelfile == null)
{
ModelState.AddModelError("excel", "Please Input the file!");
//return RedirectToAction("Index", "DataUpload");
return View("Index");
}
.........
}
I want to get the name of excelfile and check it whether the name is correct or not. If its correct then it will go to the next process. If not, it will return into view ("index"). How can I do it?
Thanks for the help.
The type HttpPostedFileBase has a FileName property that you should be able to reference with:
var fileName = excelfile.FileName;
NOTE: older browsers may not supply this value if I remember correctly.
var fname = excelfile.FileName;

Path is not a valid virtual path while uploading image to server in asp.net mvc

I want to upload image to the server, but image can be uploaded locally to a project folder with ~/images/profile, but if I use full path, it does not upload to the server. The code which I am using is given below with a sample url. Please help to solve my problem. I have seen other links of stackoverflow, but they are not working. It gives error message of path is not a valid. Virtual path and the SaveAs method is configured to require a rooted path, and the path is not rooted.
public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("http://sampleApp.com/images/profile/"), pic);
file.SaveAs(path);
db.AddTotbl_Image(new tbl_Image() { imagepath = "http://sampleApp.com/images/profile/" + pic });
db.SaveChanges();
}
return View("FileUploaded", db.tbl_Image.ToList());
}
Why do you use site name ("http://sampleApp.com") in your code? I think you don't need that on saving.
public ActionResult FileUpload(HttpPostedFileBase file, tbl_Image model)
{
if (file != null)
{
string fileName = System.IO.Path.GetFileName(file.FileName);
string fullPath = System.IO.Path.Combine(Server.MapPath("~/images/profile"), fileName);
file.SaveAs(fullPath);
db.AddTotbl_Image(new tbl_Image() { imagepath = "http://sampleApp.com/images/profile/" + fileName });
db.SaveChanges();
}
return View("FileUploaded", db.tbl_Image.ToList());
}
You also can save only fileName in db for general goal. Because in future URL can change. (By domain name, SSL etc.)
Server.MapPath should not contain an url. That's for sure.
Also, don't use
string pic = System.IO.Path.GetFileName(file.FileName);
but just
string pic = file.FileName;

Saving an image from HTML form in ASP.net MVC 3 C#

I'm hoping someone can modify my code below to show me exactly how to get this to do what I want.
I have an HTML form that posts to the following action:
public ActionResult Create(string EntryTitle, string EntryVideo, HttpPostedFileBase ImageFile, string EntryDesc)
{
if (Session["User"] != null)
{
User currentUser = (User)Session["User"];
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(ImageFile.FileName));
ImageFile.SaveAs(savedFileName);
Entry newEntry = new Entry();
newEntry.Title = EntryTitle;
newEntry.EmbedURL = EntryVideo;
newEntry.Description = EntryDesc;
newEntry.ImagePath = savedFileName;
newEntry.UserId = currentUser.UserId;
db.Entries.Add(newEntry);
db.SaveChanges();
}
return RedirectToAction("MyPage", "User");
}
This saves the image to the root solution directory (or tries to, doesn't have permission and throws exception instead).
What I would like it to do is the following:
1.) Verify that the file size is under some maximum, let's say 500kb for now
2.) Assuming file size is okay, save it to the following directory
mywebsite.com/uploads/<userid>/<entryid>/entry-image.<jpg/png/gif>
I'm not sure how to rename the file since I want to accept different file extensions (.jpeg, .jpg, .png, .gif). Or unsure how to get it into the correct directory like above. Or how to validate file size, since apparently you can only do that with javascript if the user is using IE.
1.Verify that the file size is under some maximum, let's say 500kb for now
You can use the HttpPostFileBase.ContentLength property to get the size (in bytes) of the file.
if (ImageFile.ContentLength > 1024 * 500) // 1024 bytes * 500 == 500kb
{
// The file is too big.
}
2.Assuming file size is okay, save it to the following directory
string savedFileName = Server.MapPath(string.Format("~/uploads/{0}/{1}/entry-image{2}",
currentUser.UserId,
newEntry.EntryId,
Path.GetExtension(ImageFile.FileName)));
The only problem I see is that it looks like your Entry.EntryId might be generated at the database so you won't be able to use it as part of the save path until it's been generated.
hope this helps or at least points you in the right direction
if (ImageFile.ContentLength < 1024 * 500)
{
Entry newEntry = new Entry();
newEntry.Title = EntryTitle;
newEntry.EmbedURL = EntryVideo;
newEntry.Description = EntryDesc;
newEntry.UserId = currentUser.UserId;
db.Entries.Add(newEntry);
db.SaveChanges(); //this helps generate an entry id
string uploadsDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads");
string userDir = Path.Combine(uploadsDir, <userid>);
string entryDir = Path.Combine(userDir, newEntry.EntryID );
if (Directory.Exists(userDir) == false)
Directory.CreateDirectory(userDir);
if (Directory.Exists(entryDir) == false)
Directory.CreateDirectory(entryDir);
string savedFileName = Path.Combine(entryDir, <entry-image>);
ImageFile.SaveAs(savedFileName);
newEntry.ImagePath = savedFileName; //if this doesn't work pull back out this entry and adjust the ImagePath
db.SaveChanges();
}
You should grant a write permission to the 'uploads' directory.
you can also limit file sizes for your web app from the web.config
<system.web>
<httpRuntime maxRequestLength="500"/>

Categories