日期:2014-05-18 浏览次数:20589 次
/// <summary> /// 上传单个文件 /// </summary> /// <param name="File1">文件控件</param> /// <param name="sizes">上传大小限制,KB单位;为小于等于0不限</param> /// <param name="filetype">文件后缀限定,以“|”隔开,不带"."号。为空不限</param> /// <param name="filepath">上传到文件夹路径,为空为当前文件夹</param> /// <param name="returnmessage">上传返回信息</param> /// <returns>返回上传的文件名虚拟路径</returns> public static string UploadFile(System.Web.UI.HtmlControls.HtmlInputFile File1, int sizes, string filetype, string filepath,ref string returnmessage) { returnmessage = ""; try { filepath = filepath.Trim(); if (filepath.LastIndexOf("/") != filepath.Length - 1) { filepath += "/"; } string path = filepath; //保存至的文件夹 if (path == "") { path = "./"; } path = System.Web.HttpContext.Current.Server.MapPath(path); //判断是否有上传的文件 string sourcepath = File1.Value.Trim();//文件的上传的路径 if (sourcepath == "" || sourcepath == null) { returnmessage = "无上传文件"; return ""; } string tfiletype = sourcepath.Substring(sourcepath.LastIndexOf(".") + 1).ToLower(); //如果要求的后缀不为空则判断上传的文件的后缀是否合适 if (filetype != "") { if ((filetype.ToLower() + "|").IndexOf(tfiletype + "|") < 0) { returnmessage = "上传的文件类型不符合设定"; return ""; } } if (sizes > 0) { int sizes2 = sizes * 1024; //获得上传文件的大小 long strLen = File1.PostedFile.ContentLength; //判断上传文件大小 if (strLen > sizes2) { returnmessage = "上传的文件不能大于" + sizes.ToString() + "KB"; return ""; } } System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path); //判断文件夹否存在,不存在则创建 if (!dir.Exists) { dir.Create(); } string modifyfilename = Tools.GetId(0,12); path = path + modifyfilename + "." + tfiletype; while (System.IO.File.Exists(path)) { modifyfilename = Tools.GetId(0, 12); path = path + modifyfilename + "." + tfiletype; } File1.PostedFile.SaveAs(path); filepath = filepath + modifyfilename + "." + tfiletype; returnmessage = "上传成功"; return filepath; } catch { returnmessage = "上传出现错误"; return ""; } }
------解决方案--------------------
string fileType = this.upSheetFile.PostedFile.ContentType;
if (fileType != "text/xml")
{
this.lblErr.Text = "上传文件类型不正确!";
return;
}
if (this.upSh