using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
public class Upfield : System.Web.UI.Page
{
public Upfield()
{
}
public void Upfile(FileUpload Fiup2)
{
string savePath = (System.Web.HttpContext.Current.Server.MapPath("..\\..\\FileSave" + "\\" + Session["id"]));
string[] allowExtensions = { ".doc",".docx",".pptx",".ppt",".xls",".xlsx",".jpg",".jpeg",".gif",".png","pdf",".rar",".zip",".7z",".txt" };
string fileExtensi = System.IO.Path.GetExtension(Fiup2.FileName).ToLower();
int a = 0;
for (int i = 0; i < allowExtensions.Length; i++)
{
if (fileExtensi == allowExtensions[i])
a=1;
}
if (!Directory.Exists(savePath))
{
Directory.CreateDirectory(savePath);
}
else
{
if (Fiup2.HasFile)
{
if (a != 0)
{
if (Fiup2.PostedFile.ContentLength < 10485760)
{
try
{
string fileName = Fiup2.FileName;
HttpPostedFile postFile = Fiup2.PostedFile;
string dfileName = Path.GetFileName(Fiup2.FileName).Replace(Path.GetExtension(Fiup2.FileName), " ").Replace("+", " ");
string lfileType = fileName.Substring(fileName.LastIndexOf(".") + 1);
string time1 = DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace("-", "").Replace(" ", "");
String lfileName = dfileName + time1 + "." + lfileType;
Fiup2.SaveAs(System.Web.HttpContext.Current.Server.MapPath("..\\..\\FileSave" + "\\" + Session["id"] + "\\" + lfileName));
String fileType = Fiup2.PostedFile.ContentType;
int fileSize = Fiup2.PostedFile.ContentLength;
String fileMapPath = "..\\..\\FileSave" + "\\" + Session["id"] + "\\" + Fiup2.FileName; //上傳檔案夾的路徑,自己修改
String fileTime = DateTime.Now.ToString();
/*Static.setSuZu(fileName, lfileName, fileType, fileSize, fileMapPath, Static.i); //寫入預存數組
Static.i++; //i++;*/ 為多檔案上傳做的標記,可不用
}
catch (Exception ex)
{
throw new Exception("上傳發生錯誤!");
}
}
else
{
throw new Exception("請上傳小於10M的檔案");
}
}
else
{
throw new Exception("請上傳合適的檔案類型");
}
}
else
{
throw new Exception("請選擇要上傳的檔案!");
}
}
}
}
這是檔案上傳封裝類,需要時,自己調用,調用方法如下:
protected void BtFadd_Click(object sender, EventArgs e) //上傳
{
try
{
Upfield up = new Upfield();
up.Upfile(Fiup2);
}
catch(Exception ex)
{
Response.Write("<script language='javascript'>alert('"+ex.Message+"')</script>");
}
}