首先介绍FileUpload的几个属性和方法
HasFile
FileContent
PostedFile
SaveAs方法
然后是FileUpload.PostedFile(该属性使用HttpPostedFile对象)而HttpPostedFile的一些属性和方法如下
PostedFile 属性获取使用 FileUpload 控件上载的文件的基础 HttpPostedFile 对象。使用该属性还可访问上载文件的其他属性。
可以使用 ContentLength 属性来获取文件的长度。可以使用 ContentType 属性来获取文件的 MIME 内容类型。此外,可以使用 PostedFile 属性来访问 FileName 属性、InputStream 属性和 SaveAs 方法。但是,FileName 属性、FileContent 属性和 SaveAs 方法也提供相同的功能。
{
//功能说明:上传歌曲信息
HttpFileCollection FileCollect;
FileCollect = HttpContext.Current.Request.Files;
HttpPostedFile myfile = upfile.PostedFile;
if (myfile.FileName == null)
{
return false;
}
//限制歌曲类型为mp3文件
if ((myfile.FileName.Substring(myfile.FileName.Length - 4, 4).ToUpper() != ".MP3"))
{
return false;
}
//获取歌曲大小
o_song.fsize = myfile.ContentLength.ToString();
//获取歌曲存储路径
o_song.fpath = getdirinfo() + "/" + getfilename() + ".mp3";
string temppath = savepath + o_song.fpath;
try
{
//上传歌曲
myfile.SaveAs(temppath);
}
catch (System.Exception err)
{
throw err;
return false;
}
return true;
}
public string getdirinfo()
{
FUN fun = new FUN();
string upload_absolutepath = savepath;
//根据当前月份生成文件存储文件夹,长度为两位
string dirname = System.DateTime.Today.Month.ToString("00");
StringBuilder temppath = new StringBuilder();
//将文件存储绝对路径与存储文件夹进行合并
temppath.AppendFormat("{0}{1}/", upload_absolutepath, dirname);
//对存储文件夹进行判断,如果文件夹不存在,则创建
if (!fun.Checkpath(temppath.ToString(), "dir"))
{
fun.BuildDir(temppath.ToString());
}
//返回当前生成文件夹
return dirname.ToString();
}
public string getfilename()
{
StringBuilder tempfilename = new StringBuilder();
//获取当前年份
tempfilename.AppendFormat("{0}", System.DateTime.Today.Year.ToString());
//获取当前月份
tempfilename.AppendFormat("{0}", System.DateTime.Today.Month.ToString());
//获取当前日
tempfilename.AppendFormat("{0}", System.DateTime.Today.Day.ToString());
//获取当前小时
tempfilename.AppendFormat("{0}", System.DateTime.Now.Hour.ToString());
//获取当前分钟
tempfilename.AppendFormat("{0}", System.DateTime.Now.Minute.ToString());
//获取当前秒
tempfilename.AppendFormat("{0}", System.DateTime.Now.Second.ToString());
return tempfilename.ToString();
}
public bool Checkpath(string strpath, string flag)
{
//flag dir 文件夹 file 文件
//注:该项只针对绝对路径
if (flag == "dir")
{
//判断指定路径文件夹是否存在
// 如果存在,则返回true;否则返回false
return System.IO.Directory.Exists(strpath);
}
else
{
//判断指定路径文件是否存在
//如果存在,则返回true;否则返回false
return System.IO.File.Exists(strpath);
}
}
public bool BuildDir(string strpath)
{
// dirname 文件夹名称
try
{
//按照指定路径创建文件夹
System.IO.Directory.CreateDirectory(strpath);
}
catch (System.Exception e)
{
throw e;
return false;
}
return true;
}