我正在使用asp.net C#FIleUpload。我面臨一個問題,那就是當我上傳一張圖片並將其存儲在指定的文件夾中時,刷新頁面後圖片會再次上載多次,因爲頁面已刷新。我嘗試啓用和禁用ViewState選項,但同樣的問題仍然存在。當我上傳圖片時,我已經編寫了我的功能,它將立即得到一個唯一的名稱,所以圖片不會被覆蓋。任何人都可以解釋如何控制這種行爲,以便圖片只上傳到指定的上傳按鈕上,而不是刷新頁面。 下面是我使用的主要代碼:FileUpload在頁面刷新上傳不需要的文件
protected void btnUpload_Click(object sender, EventArgs e)
{
if ((Session["Img1"] != null) && (Session["Img2"] != null) && (Session["Img3"] != null) && (Session["Img4"] != null))
{
lblUploadMsg.Text = "You cannot upload more than 4 pictures";
return;
}
if (FileUpload1.HasFile)
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() == ".jpg")
{
int fileSize = FileUpload1.PostedFile.ContentLength;
if (FileUpload1.PostedFile.ContentLength < 2097152)
{
//FileUpload1.SaveAs(Server.MapPath("~/Temp/" + FileUpload1.FileName));
//Response.Write("Successfully Done");
string sp = Server.MapPath("~/ItemPictures/");
String fn = Guid.NewGuid().ToString() + FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf("."));
if (sp.EndsWith("\\") == false)
sp += "\\";
sp += fn;
FileUpload1.PostedFile.SaveAs(sp);
lblUploadMsg.ForeColor = System.Drawing.Color.Green;
lblUploadMsg.Text = "Picture Uploaded succefully. You can upload upto 4 pictures";
Aziz.InnerHtml += "Image saved\n";
if (Session["Img1"] == null)
{
Session["Img1"] = "~/ItemPictures/" + fn;
}
else if (Session["Img2"] == null)
{
Session["Img2"] = "~/ItemPictures/" + fn;
}
else if (Session["Img3"] == null)
{
Session["Img3"] = "~/ItemPictures/" + fn;
}
else if (Session["Img4"] == null)
{
Session["Img4"] = "~/ItemPictures/" + fn;
}
}
else
{
lblUploadMsg.Text = "Maximum 2MB files are allowed";
}
}
else
{
lblUploadMsg.Text = "Only JPG files are allowed";
}
}
else
{
lblUploadMsg.Text = "No File was Selected";
}
ShowAvailblImgs();
}
private void ShowAvailblImgs()
{
if (Session["Img1"] != null)
{
Image1.ImageUrl = (string)Session["img1"];
Image1.Width = 130;
Image1.Height = 130;
Image1.Visible = true;
}
else
Image1.Visible = false;
if (Session["Img2"] != null)
{
Image2.ImageUrl = (string)Session["img2"];
Image2.Width = 130;
Image2.Height = 130;
Image2.Visible = true;
}
else
Image2.Visible = false;
if (Session["Img3"] != null)
{
Image3.ImageUrl = (string)Session["img3"];
Image3.Width = 130;
Image3.Height = 130;
Image3.Visible = true;
}
else
Image3.Visible = false;
if (Session["Img4"] != null)
{
Image4.ImageUrl = (string)Session["img4"];
Image4.Width = 130;
Image4.Height = 130;
Image4.Visible = true;
}
else
Image4.Visible = false;
}
您可以保留上傳文件的MD5校驗和緩存。對於新上傳,請檢查上傳文件的MD5。您還可以在頁面的隱藏字段中添加令牌。如果在緩存中未找到提交的令牌,則可以保存圖像。如果找到了,用戶已經提交了一個文件。在成功上傳時,用戶需要一個新的令牌。 – Amy
感謝您的推薦。如果有人知道,我還在尋找其他建議。 – user2599269
如果您使用的是' –