【问题标题】:Error uploading file in ASP .NET MCV 1.0在 ASP .NET MVC 1.0 中上传文件时出错
【发布时间】:2015-12-16 12:20:52
【问题描述】:

这是我上传文件的控制器

控制器:

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

}
}

当我执行代码时,我得到了这个错误:

“/”应用程序中的服务器错误。

'~/Content/C:\Documents and Settings\adryan\My Documents\test.xlsx' 不是有效的虚拟路径。 说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: c# asp.net asp.net-mvc file-upload


    【解决方案1】:

    您应该从文件路径中获取文件名。您可以使用Path.GetFileName 方法来做到这一点。该方法返回指定路径字符串的文件名和扩展名。

    string fileName = Path.GetFileName(excelfile.FileName);
    string path = Path.Combine(Server.MapPath("~/Content"), fileName);
    excelFile.SaveAs(path);
    

    【讨论】:

      【解决方案2】:

      这段代码会报错:

      string path = System.Web.HttpContext.Current.Server.MapPath("~/Content/" + excelfile.FileName);
      
      if (System.IO.File.Exists(path)) // <--- error here !
      

      如何解决!

      excelfile.FileName 这是 HttpPostedFileBase 的属性 excelfile .. 这是一个 FilePath !您应该使用字符串的 split('\') 方法和 LinQ 仅获取文件名来获取最后一个索引

      示例:excelfile.FileName.Split('\\').Last()

      附:对不起我的英语 >.

      请帮忙!

      【讨论】:

        猜你喜欢
        • 2016-07-25
        • 2021-12-23
        • 2013-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-20
        • 1970-01-01
        • 2017-05-12
        相关资源
        最近更新 更多