使用 ASP.NET MVC 将文件上传到子目录中的 Web 应用程序

Uploading files to Web Application in a sub-dirctory using ASP.NET MVC

我制作了一个 ASP.NET MVC 网络应用程序,它存在于一个子目录中。问题是每次我尝试上传文件时都会收到此错误“找不到路径的一部分”。

代码在我的本地机器和其他网络应用程序上运行良好,所以我认为问题与子目录中存在的网络应用程序有关,但我不知道如何解决它。

提前致谢。

这是我的功能

public byte newImage(HttpPostedFileBase newFile, string uploadPath)
        {
            if (newFile != null && newFile.ContentLength > 0)
            {
                if (newFile.ContentLength > 3000000) //means file size maximum is 3 MB
                    return 1;   //means the file size is more than 3 MB
                var fileName = Path.GetFileName(newFile.FileName);
                var path = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(uploadPath), fileName);
                newFile.SaveAs(path);
                return 0;   //means file uploaded successfuly
            }
            return 2;   //means no file was chosen
        }//Upload New Image

您 "map" 上传文件夹设置正确了吗?您可以阅读更多 here.

DirectoryInfo yourUploadDir = new DirectoryInfo(HostingEnvironment.MapPath("~/YourUploadFolder"));

我知道出了什么问题。好像忘了加上~-_-

因此,如果有人遇到此错误,请首先检查您是否忘记添加 ~。我想它在我的本地机器和其他网络应用程序上运行良好,因为它们位于根目录中,但是一旦它被放置在子目录中,我们需要使用波浪号 ~.

的相对路径