0
//Directory where images are stored on the server
String dist = "~/ImageStorage";

//get the file name of the posted image
string imgName = image.FileName.ToString();

String path = Server.MapPath("~/ImageStorage");//Path

//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
    System.IO.Directory.CreateDirectory(MapPath(path)); //Create directory if it doesn't exist
}

//sets the image path
string imgPath = path + "/" + imgName;

//get the size in bytes that
int imgSize = image.PostedFile.ContentLength;


if (image.PostedFile != null)
{

    if (image.PostedFile.ContentLength > 0)//Check if image is greater than 5MB
    {
        //Save image to the Folder
        image.SaveAs(Server.MapPath(imgPath));

    }

}

我想在服务器上创建一个文件夹目录,如果应用程序是,该文件夹应该存储用户上传的所有图像。上面的代码不起作用:

“/”应用程序中的服务器错误。'c:/users/lameck/documents/visual studio 2012/Projects/BentleyCarOwnerAssociatioServiceClient/BentleyCarOwnerAssociatioServiceClient/ImageStorage' 是物理路径,但应该是虚拟路径。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.Web.HttpException: 'c:/users/lameck/documents/visual studio 2012/Projects/BentleyCarOwnerAssociatioServiceClient/BentleyCarOwnerAssociatioServiceClient/ImageStorage' 是物理路径,但应该是虚拟路径。

源错误:

第 36 行:if (!System.IO.Directory.Exists(path)) 第 37 行:{ 第 38 行:System.IO.Directory.CreateDirectory(MapPath(path)); //如果目录不存在则创建第 39 行: } 第 40 行:

源文件:c:\Users\Lameck\Documents\Visual Studio 2012\Projects\BentleyCarOwnerAssociatioServiceClient\BentleyCarOwnerAssociatioServiceClient\registerCar.aspx.cs 行:38

4

1 回答 1

1

您不应该对同一路径使用两次 MapPath()。

旧代码:

System.IO.Directory.CreateDirectory(MapPath(path)); //Create directory if it doesn't exist

更正的代码:

System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist

编辑:还纠正了这一点:

string imgPath = path + "/" + imgName;

对此:

string imgPath = Path.Combine(path, imgName);

整个更正的代码:

  //get the file name of the posted image
    string imgName = image.FileName.ToString();

    String path = Server.MapPath("~/ImageStorage");//Path

    //Check if directory exist
    if (!System.IO.Directory.Exists(path))
    {
        System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
    }

    //sets the image path
    string imgPath = Path.Combine(path, imgName);

    //get the size in bytes that
    int imgSize = image.PostedFile.ContentLength;


    if (image.PostedFile != null)
    {

        if (image.PostedFile.ContentLength > 0)//Check if image is greater than 5MB
        {
            //Save image to the Folder
            image.SaveAs(imgPath);

        }

    }
于 2013-05-25T16:10:39.733 回答