首页 > 解决方案 > 上传图片时出现 FileNotFoundException

问题描述

在此处输入图像描述

我的目标是用户可以从他们的桌面上的任何地方选择一张图片,并将其上传/推文到 Twitter。我正在努力设置 imagePath 变量的相对路径。

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

解决了以下问题

字符串文件路径;字符串图像路径 = "";

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

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

解决方案


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

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

使用以下说明

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

亲切地


推荐阅读