今天在使用ext.net的UploadField控件想上傳文件時,發現examples.ext.net官網上的例子寫的不是很詳細。於是通過網上找資料,結合asp.net的文件上傳的方法,終於實現了圖片的上傳功能。以下就是實現的代碼,供大家參考!
首先在.aspx文件中插入一個文件上傳的控件:
<ext:FileUploadField ID="UploadFile" runat="server" FieldLabel="附件上傳" ButtonText="瀏覽..."/>
然后是.cs文件中實現上傳的具體代碼:
string UploadFile ="";
if (this.UploadFile.HasFile)
{
UploadFile = this.UploadFile.PostedFile.FileName.ToString();
int FileSize=Int32.Parse(this.UploadFile.PostedFile.ContentLength.ToString());
if (FileSize > 5 * 1024 *1024)
{
X.Msg.Alert("提示信息", "上傳文件過大!").Show();
return;
}
string strFileName = Path.GetExtension(this.UploadFile.PostedFile.FileName).ToUpper();//獲取文件后綴
if (!(strFileName == ".BMP" || strFileName == ".GIF" || strFileName == ".JPG"))
{
X.Msg.Alert("提示信息", "文件格式不正確!").Show();
return;
}
Random ran = new Random();
string sNewName = DateTime.Now.ToString(@"yyyyMMddHHmmss") + ran.Next(100, 999)
+ Path.GetExtension(this.UploadFile.PostedFile.FileName);
string strPath = Server.MapPath("~/FileUpload/" + sNewName);
if (!Directory.Exists(Path.GetDirectoryName(strPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(strPath));
}
this.UploadFile.PostedFile.SaveAs(strPath);
}
通過簡單的操作,就是給上傳的圖片重新命名,並且保存到要保存的文件夾中。
