我正在制作投诉表格。在这个表单中,我必须创建一个上传文件然后删除上传文件的函数。我可以将文件上传到服务器,但是我无法将我上传到服务器的文件的链接删除。请帮我。这是我的代码:
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;
}
}
答案 0 :(得分:1)
asp.net中的每个请求都会创建一个页面的新对象 如果在一个请求期间设置变量,则在下一个请求中它们将不可用。
您的删除逻辑似乎取决于在上传期间设置的FilePath
。如果您希望页面记住该页面,请将其保留在ViewState中。 ViewState在对同一页面的请求之间进行维护,并允许您在删除期间使用变量FilePath
。
这可以通过使FilePath
属性并从ViewState获取它来轻松实现。
public string FilePath
{
get
{
return (string) ViewState["FilePath"];
}
set
{
ViewState["FilePath"] = value;
}
}
答案 1 :(得分: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);
}
使用此代码,您可以将文件上传到站点根目录中的特定位置。 并且路径将作为字符串存储在数据库中。 所以你只需使用存储在数据库中的路径就可以访问该文件。 如果你什么都不懂。或者想知道更多你可以联系我或在评论中问我。