Reputation: 71
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());
}
Upvotes: 0
Views: 11293
Reputation: 3787
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.)
Upvotes: 1
Reputation: 156978
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;
Upvotes: 0