首页 文章

在asp.net mvc中将图像上传到服务器时,路径不是有效的虚拟路径

提问于
浏览
0

我想将图像上传到服务器,但图像可以使用 ~/images/profile 本地上传到项目文件夹,但如果我使用完整路径,则不会上传到服务器 . 我正在使用的代码在下面给出了一个示例网址 . 请帮忙解决我的问题 . 我已经看到了stackoverflow的其他链接,但它们无法正常工作 . 它给出路径的错误消息是无效的 . 虚拟路径和 SaveAs 方法配置为需要根路径,并且路径不是root .

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

2 回答

  • 1

    为什么在代码中使用站点名称(“http://sampleApp.com”)?我认为你不需要保存 .

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

    您还可以在db中保存 only fileName 以获得一般目标 . 因为将来URL可以改变 . (按域名,SSL等)

  • 0

    Server.MapPath不应包含url . 这是肯定的 .

    另外,不要使用

    string pic = System.IO.Path.GetFileName(file.FileName);
    

    只是

    string pic = file.FileName;
    

相关问题