㈠ 页面上有一个文件上传控件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;
}