上载图片时出现FileNotFoundException

时间:2019-11-14 19:54:30

标签: asp.net asp.net-mvc asp.net-mvc-5

enter image description here

我的目标是用户可以从桌面上的任意位置选择图片,并将其上传/推特到Twitter。我正在努力设置imagePath变量的相对路径。

路径(D驱动器)存储了我的图像。在运行应用程序时,它看起来在不同的路径中。这将引发错误System.IO.FileNotFoundException。我也尝试过Server.MapPath。协助我解决它。

解决了以下问题

string filePath;字符串imagePath =“”;

        if (imgFile == null)
        {
            imgFile = Request.Files["imgFile"];
        }

        if (imgFile.FileName != "")
        {
            filePath = Server.MapPath("~/Images/");
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = filePath + Path.GetFileName(imgFile.FileName);
            imgFile.SaveAs(filePath);
            imagePath = Path.Combine(Server.MapPath(@"~/Images/"), filePath);
        }

1 个答案:

答案 0 :(得分:0)

文件必须保存在服务器位置,请尝试替换以下说明:

string imagePath=Path.Combine(Request.MapPath("~/"),fileName);

按照以下说明

var fileName = Path.GetFileName(file.FileName);  
var imagePath = Path.Combine(Request.MapPath("~/"), fileName);
file.SaveAs(imagePath); 
........

私下