2

我正在制定投诉表。在这个表单中,我必须创建一个上传文件的函数,然后删除上传的文件。我可以将文件上传到服务器,但我无法获取上传到服务器的文件的链接以删除它。请帮我。这是我的代码:

public string FilePath;
protected void btAdd_Click(object sender, EventArgs e)
    {          
    if (AttachFile.HasFile)
        {
            try
            {
                    string[] sizes = {"B", "KB", "MB", "GB"};
                    double sizeinbytes = AttachFile.FileBytes.Length;
                    string filename = Path.GetFileNameWithoutExtension(AttachFile.FileName);
                    string fileextension = Path.GetExtension(AttachFile.FileName);
                    int order = 0;
                    while (sizeinbytes >= 1024 && order + 1 < sizes.Length)
                    {
                        order++;
                        sizeinbytes = sizeinbytes/1024;
                    }
                    string result = String.Format("{0:0.##} {1}", sizeinbytes, sizes[order]);
                    string encryptionFileName = EncrytionString(10);                       
                    FilePath = "Path" + encryptionFileName.Trim() + AttachFile.FileName.Trim();
                    AttachFile.SaveAs(FilePath);                    
            }
            catch (Exception ex)
            {
                lbMessage.Visible = true;
                lbMessage.Text = ex.Message;
            }
        }
    } 

protected void btDelete_Click(object sender, EventArgs e)
    {
        try
        {
            File file = new FileInfo(FilePath);
            if (file.Exists)
            {
                File.Delete(FilePath);
            }
        }
        catch (FileNotFoundException fe)
        {
            lbMessage.Text = fe.Message;
        }
        catch (Exception ex)
        {
            lbMessage.Text = ex.Message;
        }
    }
4

2 回答 2

1

asp.net 中的每个请求都会为您的页面创建一个新对象。
如果您在一个请求期间设置变量,它们在下一个请求中将不可用。

您的删除逻辑似乎取决于FilePath在上传期间设置。如果您希望页面记住这一点,请将其保存在 ViewState 中。ViewState 在对同一页面的请求之间得到维护,这将允许您FilePath在删除期间使用该变量。

这可以通过创建FilePath一个属性并从 ViewState 中获取来轻松实现。

public string FilePath
{
  get
  {
    return (string) ViewState["FilePath"];
  }
  set
  {
    ViewState["FilePath"] = value;
  }
}
于 2013-04-08T06:47:58.350 回答
0

你应该这样做。

if (imgUpload.HasFile)
     {
                String strFileName = imgUpload.PostedFile.FileName;
                imgUpload.PostedFile.SaveAs(Server.MapPath("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
                SqlCommand cmd01 = new SqlCommand("insert into img (FeaturedImg) Values (@img)", cn01);
                    cmd01.Parameters.AddWithValue("@img", ("\\DesktopModules\\Indies\\FormPost\\img\\") + strFileName);
      }

使用此代码,您可以将文件上传到站点根目录中的特定位置。并且路径将作为字符串存储在数据库中。因此您只需使用存储在数据库中的路径即可访问该文件。如果你什么都看不懂。或者想知道更多你可以联系我或在评论中问我。

于 2013-04-08T06:54:53.620 回答