ASP.NET:图像URL正确,但是图像不显示

时间:2020-02-26 21:46:47

标签: c# asp.net image-uploading web-controls

我知道这是一个菜鸟问题,以前已经有人问过,但是这里的其他答案并没有为我澄清。我正在上传文件,然后提供预览。我的上传按钮的点击事件是这样的:

protected void UploadFile (object sender, EventArgs e) {

    string folderPath = Server.MapPath ("~/Uploads/");

    // If folder does not exist, create it.
    if (!Directory.Exists (folderPath))
        Directory.CreateDirectory (folderPath);         

    //Save the File to the Directory (Folder).
    FileUpload.SaveAs (folderPath + Path.GetFileName (FileUpload.FileName));

    //Display the Picture in Image control.
    imgItem.ImageUrl = folderPath + Path.GetFileName (FileUpload.FileName);
}

上传正常,但是图像控件(imgItem)不显示图片。当我跟踪它时,URL看起来很完美。网址是:

"C:\\MyStuff\\Source\\Inventory\\Inventory\\UserInterface\\Uploads\\sample.jpg"

那应该有效。我到底在做错什么?

编辑:我根本感觉不到这是一个好的解决方案,但是我发现如果将最后一行更改为此,程序将按预期工作:

imgItem.ImageUrl = "~/Uploads/" + Path.GetFileName (FileUpload.FileName);

没有人有一个更干净,硬编码更少的解决方案吗?

2 个答案:

答案 0 :(得分:0)

好吧

“ C:\ MyStuff \ Source \ Inventory \ Inventory \ UserInterface \ Uploads \ sample.jpg”

实际上是文件路径,而不是URL。由于您使用的是“ URL”一词,因此我假设您正在构建一个网站。这意味着您需要一个正确的网址(例如http(s)://yourdomain.com/Source/Inventory/..../sample.jpg)

如果您不知道文件路径的URL是什么,则可以使用IIS中的虚拟文件夹进行映射。 https://docs.kentico.com/k11/installation/deploying-kentico-to-a-live-server/creating-virtual-directories-and-application-pools-in-iis-7-5-and-7-0

答案 1 :(得分:0)

imgItem.ImageUrl =“〜/ Uploads /” + Path.GetFileName(FileUpload.FileName);

相关问题