小菜分享下自己的思路,不知道各位有木有更好的方法
源碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//MyBlog:http://seay.sinaapp.com/
}
protected void Button1_Click(object sender, EventArgs e)
{
#region 文件類型判斷
//得到上傳文件名
string FileName = FileUpload1.FileName;
//判斷文件名中有木有.
if (!(FileName.Contains(".")))
{
Response.Write("該文件類型不允許上傳!");
return;
}
//取到.的下標(biāo)
int index = FileName.LastIndexOf('.');
char[] c = FileName.ToCharArray();
string File_hz = "";
//循環(huán)得到后綴名
for (int i = 0; i < FileName.Length - index; i++)
{
File_hz += c[index + i];
}
//允許上傳的文件名
string[] FileType = { ".jpg", ".gif", ".bmp", ".jpeg" };
bool bl = false;
//循環(huán)遍歷上傳的文件擴(kuò)展名是否在允許的擴(kuò)展名中
foreach (string str in FileType)
{
if (str == File_hz)
{
bl = true;
}
}
if (bl == false)
{
Response.Write("該文件類型不允許上傳!");
return;
}
#endregion
//獲取時(shí)間戳給文件命名,這樣寫(xiě)感覺(jué)有點(diǎn)復(fù)雜,不知道各位有木有好的方法獲取時(shí)間戳
DateTime starttime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
DateTime newtime = DateTime.Now;
long utime = (long)Math.Round((newtime - starttime).TotalMilliseconds, MidpointRounding.AwayFromZero);
FileName = utime.ToString() + File_hz;
//獲取文件字節(jié)數(shù)
string FileLenght = FileUpload1.PostedFile.ContentLength.ToString();
string FilePath = Server.MapPath("img/" + FileName);
//上傳
FileUpload1.SaveAs(FilePath);
Response.Write("上傳成功<br />文件大?。? + FileLenght + "<br />路徑:img/" + FileName);
}
}
聯(lián)系客服