這篇文章主要介紹了ASP.NET實現的簡單易用文件上傳類,本文給出實現代碼和使用方法示例,需要的朋友可以參考下
調用方法:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 UploadFile uf = new UploadFile(); /*可選參數*/ uf.SetIsUseOldFileName(true);//是否使用原始文件名作為新文件的文件名(默認:true),true原始文件名,false系統生成新文件名 uf.SetFileDirectory(Server.MapPath("/file/temp3/"));//文件保存路徑(默認:/upload) uf.SetFileType("*");//允許上傳的文件類型, 逗號分割,必須全部小寫! *表示所有 (默認值: .pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif ) uf.SetIsRenameSameFile(false);//重命名同名文件? //文件以時間分目錄保存 var message = uf.Save(Request.Files["Fileupload1"]); // “/file/temp3/2015/4/xx.jpg” //文件以編號分目錄保存 var message2 = uf.Save(Request.Files["Fileupload1"], "001" /*編號*/); // “/file/temp3/001/xx.jpg” //返回信息 var isError = message.Error;//判段是否上傳成功 var webPath = message.WebFilePath;//返回web路徑 var msg = message.Message;//返回上傳信息 var filePath = message.FilePath;//反回文件路徑 var isSuccess = message.Error == false;代碼:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text.RegularExpressions; using System.Web; using System.Web.Hosting; namespace SyntacticSugar { /// <summary> /// ** 描述:單文件上傳類 (暫時不支持多文件上傳) /// ** 創始時間:2015-5-27 /// ** 修改時間:- /// ** 作者:sunkaixuan /// </summary> public class UploadFile { private ParamsModel Params; public UploadFile() { Params = new ParamsModel() { FileDirectory = "/upload", FileType = ".pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif", MaxSizeM = 10, PathSaveType = PathSaveType.dateTimeNow, IsRenameSameFile=true }; } /// <summary> /// 文件保存路徑(默認:/upload) /// </summary> public void SetFileDirectory(string fileDirectory) { if (fileDirectory == null) { throw new ArgumentNullException("fileDirectory"); } var isMapPath = Regex.IsMatch(fileDirectory, @"[a-z]:", RegexOptions.IgnoreCase); if (isMapPath) { fileDirectory = GetRelativePath(fileDirectory); } Params.FileDirectory = fileDirectory; } /// <summary> /// 是否使用原始文件名作為新文件的文件名(默認:true) /// </summary> /// <param name="isUseOldFileName">true原始文件名,false系統生成新文件名</param> public void SetIsUseOldFileName(bool isUseOldFileName) { Params.IsUseOldFileName = isUseOldFileName; } /// <summary> /// 允許上傳的文件類型, 逗號分割,必須全部小寫! *表示所有 (默認值: .pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif ) /// </summary> public void SetFileType(string fileType) { Params.FileType = fileType; } /// <summary> /// 允許上傳多少大小(單位:M) /// </summary> public void SetMaxSizeM(double maxSizeM) { Params.MaxSizeM = maxSizeM; } /// <summary> /// 重命名同名文件? /// </summary> /// <param name="isRenameSameFile">true:重命名,false覆蓋</param> public void SetIsRenameSameFile(bool isRenameSameFile) { Params.IsRenameSameFile = isRenameSameFile; } /// <summary> /// 保存表單文件 /// </summary> /// <param name="postFile">HttpPostedFile</param> /// <returns></returns> public ResponseMessage Save(HttpPostedFile postFile) { return CommonSave(postFile); } /// <summary> /// 保存表單文件,根據編號創建子文件夾 /// </summary> /// <param name="postFile">HttpPostedFile</param> /// <param name="number">編號</param> /// <returns></returns> public ResponseMessage Save(HttpPostedFile postFile, string number) { Params.PathSaveType = PathSaveType.code; _Number = number; return CommonSave(postFile); } /// <summary> /// 保存表單文件,根據HttpPostedFile /// </summary> /// <param name="postFile">HttpPostedFile</param> /// <param name="isRenameSameFile">值為true 同名文件進行重命名,false覆蓋原有文件</param> /// <param name="fileName">新的文件名</param> /// <returns></returns> private ResponseMessage CommonSave(HttpPostedFile postFile) { ResponseMessage reval = new ResponseMessage(); try { if (postFile == null || postFile.ContentLength == 0) { TryError(reval, "沒有文件!"); return reval; } //文件名 string fileName = Params.IsUseOldFileName ? postFile.FileName : DateTime.Now.ToString("yyyyMMddhhmmssms") + Path.GetExtension(postFile.FileName); //驗證格式 this.CheckingType(reval, postFile.FileName); //驗證大小 this.CheckSize(reval, postFile); if (reval.Error) return reval; string webDir = string.Empty; // 獲取存儲目錄 var directory = this.GetDirectory(ref webDir); var filePath = directory + fileName; if (System.IO.File.Exists(filePath)) { if (Params.IsRenameSameFile) { filePath = directory + DateTime.Now.ToString("yyyyMMddhhssms") + "-" + fileName; } else { System.IO.File.Delete(filePath); } } // 保存文件 postFile.SaveAs(filePath); reval.FilePath = filePath; reval.FilePath = webDir + fileName; reval.FileName = fileName; reval.WebFilePath = webDir + fileName; return reval; } catch (Exception ex) { TryError(reval, ex.Message); return reval; } } private void CheckSize(ResponseMessage message, HttpPostedFile PostFile) { if (PostFile.ContentLength / 1024.0 / 1024.0 > Params.MaxSizeM) { TryError(message, string.Format("對不起上傳文件過大,不能超過{0}M!", Params.MaxSizeM)); } } /// <summary> /// 根據物理路徑獲取相對路徑 /// </summary> /// <param name="fileDirectory"></param> /// <param name="sever"></param> /// <returns></returns> private static string GetRelativePath(string fileDirectory) { var sever = HttpContext.Current.Server; fileDirectory = "/" + fileDirectory.Replace(sever.MapPath("~/"), "").TrimStart('/').Replace('', '/'); return fileDirectory; } /// <summary> /// 獲取目錄 /// </summary> /// <returns></returns> private string GetDirectory(ref string webDir) { var sever = HttpContext.Current.Server; // 存儲目錄 string directory = Params.FileDirectory; // 目錄格式 string childDirectory = DateTime.Now.ToString("yyyy-MM/dd"); if (Params.PathSaveType == PathSaveType.code) { childDirectory = _Number; } webDir = directory.TrimEnd('/') + "/" + childDirectory + '/'; string dir = sever.MapPath(webDir); // 創建目錄 if (Directory.Exists(dir) == false) Directory.CreateDirectory(dir); return dir; } /// <summary> /// 驗證文件類型) /// </summary> /// <param name="fileName"></param> private void CheckingType(ResponseMessage message, string fileName) { if (Params.FileType != "*") { // 獲取允許允許上傳類型列表 string[] typeList = Params.FileType.Split(','); // 獲取上傳文件類型(小寫) string type = Path.GetExtension(fileName).ToLowerInvariant(); ; // 驗證類型 if (typeList.Contains(type) == false) this.TryError(message, "文件類型非法!"); } } /// <summary> /// 拋出錯誤 /// </summary> /// <param name="Msg"></param> private void TryError(ResponseMessage message, string msg) { message.Error = true; message.Message = msg; } #region models private class ParamsModel { /// <summary> /// 文件保存路徑 /// </summary> public string FileDirectory { get; set; } /// <summary> /// 允許上傳的文件類型, 逗號分割,必須全部小寫! /// </summary> public string FileType { get; set; } /// <summary> /// 允許上傳多少大小 /// </summary> public double MaxSizeM { get; set; } /// <summary> /// 路徑存儲類型 /// </summary> public PathSaveType PathSaveType { get; set; } /// <summary> /// 重命名同名文件? /// </summary> public bool IsRenameSameFile { get; set; } /// <summary> /// 是否使用原始文件名 /// </summary> public bool IsUseOldFileName { get; set; } } /// <summary> /// 路徑存儲類型 /// </summary> public enum PathSaveType { /// <summary> /// 根據時間創建存儲目錄 /// </summary> dateTimeNow = 0, /// <summary> /// 根據ID編號方式來創建存儲目錄 /// </summary> code = 1 } private string _Number { get; set; } /// <summary> /// 反回信息 /// </summary> public class ResponseMessage { /// <summary> /// 上傳錯誤 /// </summary> public bool Error { get; set; } /// <summary> /// 消息 /// </summary> public string Message { get; set; } /// <summary> /// 文件路徑 /// </summary> public string FilePath { get; set; } /// <summary> /// 網站路徑 /// </summary> public string WebFilePath { get; set; } /// <summary> /// 獲取文件名 /// </summary> public string FileName { get; set; } } #endregion } }