【问题标题】:Uploading an image to a folder in desktop将图像上传到桌面文件夹
【发布时间】:2017-04-30 17:47:00
【问题描述】:

我无法将图像上传到指定文件夹。这是代码。

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (FileUploader.HasFile)
    {
        try
        {
             string filename = Path.GetFileName(FileUploader.FileName);
             FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES" + filename);
             Label1.Text = "Uploaded Successfully!!";
        }
        catch (Exception ex)
        {
            Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

当我点击上传时,标签确实写着代码中的Uploaded Successfully!!,但图片不在代码中的指定文件夹中。请帮忙谢谢!

【问题讨论】:

  • 你检查过 filename 的值吗?我假设它不以 \ 开头 - 然后 FileUploader.SaveAs 中提供的文件名不会将数据存储在 PICTURES 文件夹中,而是在文件名以 PICTURES 开头的桌面文件夹中。
  • 是的,请查看文件名以 PICTURES____ 开头的桌面。上传的文件是否在桌面?

标签: c# asp.net file-upload upload directory


【解决方案1】:

尝试将您的代码更改为

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (FileUploader.HasFile)
    {
        try
        {
             string filename = Path.GetFileName(FileUploader.FileName);
             FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES\" + filename);
             Label1.Text = "Uploaded Successfully!!";
        }
        catch (Exception ex)
        {
            Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }
    }
}

我只是在 PICTURES 之后添加了一个反斜杠,以便构建正确的文件名。

【讨论】:

    【解决方案2】:

    在图片后面加上\

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (FileUploader.HasFile)
        {
            try
            {
                 string filename = Path.GetFileName(FileUploader.FileName);
                 FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES\" + filename);
                 Label1.Text = "Uploaded Successfully!!";
            }
            catch (Exception ex)
            {
                Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      问题是这一行:

      FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES" + filename);
      

      添加斜线可以解决问题:

      FileUploader.SaveAs(@"D:\Users\SGG90745\Desktop\PICTURES\" + filename);
      

      一种更与平台无关的修复方法是:

      const string folder = @"D:\Users\SGG90745\Desktop\PICTURES" 
      ...
      var path = folder + Path.DirectorySeparatorChar + filename;
      

      最好的方法是:

      const string folder = @"D:\Users\SGG90745\Desktop\PICTURES" 
      ...
      var path = Path.Combine(folder, filename);
      

      【讨论】:

        猜你喜欢
        • 2014-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-24
        • 2014-10-24
        • 2020-01-10
        相关资源
        最近更新 更多