无法上传保存在服务器上的图像

时间:2011-09-09 13:19:28

标签: asp.net file-upload

我正在服务器上保存图像文件。该文件已成功保存在服务器上,但是当我尝试将该文件的URL分配给图像控件时,图像无法加载,但是当我将该URL直接分配给HTML代码时,文件已成功加载。请指导我在哪里弄错了。以下是我的文件上传和获取网址的代码。

文件上传代码

private string ImageUpload()
{
    try
    {
        string FileName = UpldCompanyLogo.FileName;
        if (UpldCompanyLogo.HasFile)
        {
            string SaveFilePath = Server.MapPath("~\\Upload\\")+FileName;
            if (!Directory.Exists(Server.MapPath("~\\Upload\\")))
                Directory.CreateDirectory(Server.MapPath("~\\Upload\\"));

            if (File.Exists(SaveFilePath))
            {
                File.Delete(SaveFilePath);
            }
            if(File.Exists(ViewState["ImageURL"].ToString()))
            {
                File.Delete(ViewState["ImageURL"].ToString());
            }
            UpldCompanyLogo.PostedFile.SaveAs(SaveFilePath);
        }
        return FileName;

    }
    catch (Exception ex)
    {

        if (ex.HelpLink == null)
            ex.HelpLink = "Controls_Company103>>" + ex.Message;
        else
            ex.HelpLink = "Controls_Company103>>" + ex.HelpLink;
        lblMessage.Text = ex.HelpLink;
        lblMessage.CssClass = "ERROR";
        return null;
    }
}

这是获取图片网址的代码

if (dtCompany != null)
            {
                if (dtCompany.Rows.Count > 0)
                {
                    txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
                    txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
                    txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
                    txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
                     string path = Server.MapPath("~\\Upload\\");
                    imgLogo.ImageUrl = path + dtCompany.Rows[0]["CompanyLogo"].ToString();

                }
            }

如果我在浏览器中复制并浏览检索到的路径,则会在服务器上找到该图像。

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

if (dtCompany != null)
{
    if (dtCompany.Rows.Count > 0)
    {
        txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
        txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
        txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
        txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
        imgLogo.ImageUrl = Page.ResolveUrl("~\\Upload\\") + dtCompany.Rows[0]["CompanyLogo"].ToString();

    }
}