㈠ 頁面上有一個文件上傳控制項FileUpload1,旁邊用一個按鈕,點擊按鈕,如何實現上傳功能
首先給這個按鈕綁定一個後台Click事件,
protected void Submit_Click(object sender, EventArgs e)
{
UploadFilesToServer(this.fileUpload.FileName,FileEnum.FileEnumType.bookDown,imgFile);
}
/// <summary>
/// 將文件保存到伺服器
/// </summary>
/// <param name="filePath">上傳控制項中的路徑</param>
/// <param name="type">上傳文件的類型</param>
/// <param name="imgFile"></param>
/// <returns></returns>
public string UploadFilesToServer(string filePath, FileEnum.FileEnumType type, HttpPostedFile imgFile)
{
if (!string.IsNullOrEmpty(filePath))
{
string houzui = new FileInfo(filePath).Extension;
if (houzui.ToLower().Equals("." + FileEnum.FileExtension.zip.ToString()) || houzui.ToLower().Equals("." + FileEnum.FileExtension.rar.ToString()))
{
System.IO.FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
byte[] mydata = new byte[fs.Length];
int length = Convert.ToInt32(fs.Length);
fs.Read(mydata, 0, length);
string filename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + houzui;
string savePath = string.Empty;
savePath = ConfigurationManager.AppSettings["uploadFilePath"] + type.ToString() + "/" + filename;
fs = new FileStream(Context.Server.MapPath(savePath), FileMode.Create, FileAccess.Write);
fs.Write(mydata, 0, mydata.Length);
fs.Flush();
fs.Close();
return savePath;
}
return string.Empty;
}
return string.Empty;
}