Asp. NET implementation of simple File upload class

Source: Internet
Author: User
Tags bool datetime file upload httpcontext lowercase save file split

This article mainly introduces the ASP.net implementation of the simple file upload class, this article gives the implementation code and use method examples, the need for friends can refer to the

Call Method:

?

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 ()  /* Optional Parameters/UF. Setisuseoldfilename (TRUE);//Whether to use the original file name as the file name for the new file (default: TRUE), True the original filename, false the system generates a new filename uf. Setfiledirectory (Server.MapPath ("/file/temp3/"));//File Save path (default:/upload) uf. Setfiletype ("*");//Allow uploaded file type, comma split, must all lowercase! * Represents all (default:. pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif) uf. Setisrenamesamefile (false);//rename file with same name?    //files save var message = UF with a time catalog. Save (request.files["Fileupload1"]); "/file/temp3/2015/4/xx.jpg"  //files are stored in numbered directories with var message2 = uf. Save (request.files["Fileupload1"], "001"/* number */); "/file/temp3/001/xx.jpg"    //return information var isError = message. Whether the error;//to upload success var webpath = message. webfilepath;//returns the Web path var msg = message. message;//returns the upload information var filePath = message. filepath;//back to file path var issuccess = message. Error = = false;

Code:

?

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 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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 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-1 41 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-2 02 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-2 63 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>///* * Description: Single File Upload class (temporarily does not support multiple file uploads)///* * Founder Time: 2015-5-27///* * Modified Time:-///* * Author: Sunkaixuan///</summary> public class UploadFile {  private paramsmodel Params; public UPLOADF Ile () {Params = new Paramsmodel () {filedirectory = "/upload", FileType = ". Pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif ", Maxsizem = ten, Pathsavetype = Pathsavetype.datetimenow, isrenamesamefile=true};}  ///<summary>///File Save path (default:/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>///whether to use the original file name as the file name for the new file (default: TRUE)///</summary>///<param name= "Isuseoldfile Name ' >true original filename, false system generates new file name </param> public void Setisuseoldfilename (bool isuseoldfilename) { Params.isuseoldfilename = Isuseoldfilename; }  ///<summary>///allow file types to be uploaded, comma split, must all lowercase! * Represents all (default:. pdf,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif)///</summary> public void Setfiletype (string FileType) {params.filetype = FileType}///<summary>///How many sizes are allowed to upload (unit: M)///</summary> public void Setmaxsi Zem (double maxsizem) {Params.maxsizem = Maxsizem}///<summary>///rename file with same name? </summary>///<param name= "Isrenamesamefile" >true: renaming, false overwrite </param> public void Setisrenamesamefile (bool isrenamesamefile) {params.isrenamesamefile = Isrenamesamefile;}    ///<summary >///Save the form file///</summary>///<param name= "Postfile" >httppostedfile</param>///<returns></returns> public responsemessage Save (Httppostedfile postfile) { Return Commonsave (Postfile);      ///<summary>///Save form files, create subfolders by number///</summary>///<param name= "Postfile" >htt ppostedfile</param>///<param name= "number" > Code </param>///<returns></returns> Public Responsemessage Save (Httppostedfile postfile, string number) {  Params.pathsavetype = pathsavetype.code; _number = n umber; Return Commonsave (Postfile); }    ///<summary>///Save the form file, according to Httppostedfile///</summary>///<param name= "Postfile" >htt ppostedfile</param>///<param name= "Isrenamesamefile" > Value to True with the same name file for renaming, false overwrite existing file </param>/// <param name= "filename" > New filename </param>///<returns></returns> Private Responsemessage Commonsave (Httppostedfile postfile) {  Responsemessage Reval = new Responsemessage (); try {if (Postfile = =null | | Postfile.contentlength = = 0) {tryerror (Reval, "no file!") "); return Reval; }  //filename string filename = params.isuseoldfilename? PostFile.FileName:DateTime.Now.ToString ("yyyymmddhhmmssms") + path.getextension (postfile.filename);  //validation format this. Checkingtype (Reval, postfile.filename); Verify size this. Checksize (Reval, postfile);   if (Reval. Error) return Reval;     String webdir = string. Empty; Get storage directory 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);}} Save File Postfile.saveas (FilePath); Reval. FilePath = FilePath; Reval. FilePath = WebDir + fileName; Reval. filename = filename; Reval. Webfilepath = WebDir + fileName; return Reval; The 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 ("Sorry to upload the file too large, not more than {0}m! ", Params.maxsizem));} <summary>///obtain relative paths according to physical path///</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>///get directory///</summary>///<returns></returns> private String getdirectory (Ref string WebDir) {var sever = HttpContext.Current.Server;//storage directory string directory = Params.filedirectory;  /directory format string Childdire Ctory = DateTime.Now.ToString ("Yyyy-mm/dd"); if (Params.pathsavetype = = Pathsavetype.code) {childdirectory = _number;} webdir = Directory. TrimEnd ('/') + "/" + childdirectory + '/'; String dir = Sever. MapPath (WebDir); Create the directory if (directory.exists (dir) = False) Directory.CreateDirectory (dir); return dir; }  ///<summary>///validation file type)///</summary>///<param name= "fileName" ></param> private void Checkingtype (Responsemessage message, string fileName) {if (Params.filetype!= "*") {//Get Allow upload Type list string[] Typelist = Params.FileType.Split (', ');  //Get upload file type (lowercase) String type = Path.getextension (fileName). Tolowerinvariant ();;  //authentication type if (Typelist.contains (type) = = False) this. Tryerror (Message, "File type illegal!"); }  ///<summary>///throw error///</summary>///<param name= "MSG" ></param> private void Tryer ROR (Responsemessage message, string msg) {message. Error = true; Message. message = MSG; }   #region models   Private class Paramsmodel {///<summary>///file save path///</summary> public stri ng FileDirectory {get; set;}///<Summary>///allows uploading of file types, comma split, must all lowercase! </summary> public string FileType {get; set;}///<summary>///How many sizes are allowed to upload///</summary> public dou ble maxsizem {get; set;}///<summary>///path Storage type///</summary> public pathsavetype pathsavetype {get; set ; ///<summary>///Rename a file with the same name? </summary> public bool Isrenamesamefile {get; set;}///<summary>///whether to use the original filename///</summary> pub LIC bool Isuseoldfilename {get; set;}}    ///<summary>///path Storage type///</summary> public enum Pathsavetype {///<summary>///based on time creation Build Storage directory///</summary> datetimenow = 0,///<summary>///Create storage directory based on ID number///</summary> code = 1  } private string _number {get; set;}  ///<summary>///back to information///</summary> public class Responsemessag e {///<summary>///upload error///</summary> public bool Error {get; set;}///<summary>///message///</ Summary> public String Message {get; set;}///<summary>///file path///</summary> public string FilePath {get; set;}///<summar Y>///Web site path///</summary> public string Webfilepath {get; set;}///<summary>///getting file name///</summary > public string FileName {get; set;}  } #endregion}}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.