Reputation: 127
This is my controller to upload file
Controller:
namespace MvcApplication5.Controllers
{
public class DataUploadController : Controller
{
public ActionResult Index()
{
return View("Index");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Import(HttpPostedFileBase excelfile)
{
if (excelfile == null || excelfile.ContentLength == 0)
{
ModelState.AddModelError("empty", "some error message");
return RedirectToAction("Index", "DataUpload");
}
else
{
if (excelfile.FileName.EndsWith(".xls") || excelfile.FileName.EndsWith(".xlsx"))
{
string path = System.Web.HttpContext.Current.Server.MapPath("~/Content/" + excelfile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelfile.SaveAs(path);
return View("success");
}
else
{
return View("Index");
}
}
}
}
}
When I execute the code, I got this error:
'~/Content/C:\Documents and Settings\adryan\My Documents\test.xlsx' is not a valid virtual path. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Can you help me solve the problem?
Upvotes: 0
Views: 276
Reputation: 218892
You should get the file name from the file path. You may use the Path.GetFileName
method to do that. This method returns the file name and extension of the specified path string.
string fileName = Path.GetFileName(excelfile.FileName);
string path = Path.Combine(Server.MapPath("~/Content"), fileName);
excelFile.SaveAs(path);
Upvotes: 2
Reputation:
This code will thrown error :
string path = System.Web.HttpContext.Current.Server.MapPath("~/Content/" + excelfile.FileName);
if (System.IO.File.Exists(path)) // <--- error here !
How to solve !
excelfile.FileName this is properties of HttpPostedFileBase excelfile .. And this is a FilePath ! you should get only filename by use split('\') method of string and LinQ to get last index
Example :
excelfile.FileName.Split('\\').Last()
P.S. sorry for my english >.< !
Holp this help !
Upvotes: 0