Simple and Easy-to-use File Upload class implemented by ASP. NET, asp.net File Upload

Source: Internet
Author: User

Simple and Easy-to-use File Upload class implemented by ASP. NET, asp.net File Upload

Call method:

UploadFile uf = new UploadFile ();/* optional parameter */uf. setIsUseOldFileName (true); // whether to use the original file name as the new file name (default: true), true original file name, false system generates new file name uf. setFileDirectory (Server. mapPath ("/file/temp3/"); // file storage path (default:/upload) uf. setFileType ("*"); // specifies the type of files that can be uploaded. Separate them with commas (,). All files must be in lower case! * Indicates all (default value: .20.,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif) uf. SetIsRenameSameFile (false); // rename a file with the same name? // Save var message = uf in a time-based directory. save (Request. files ["Fileupload1"]); // "/file/temp3/2015/4/xx.jpg" // save var message2 = uf in the numbered directory. save (Request. files ["Fileupload1"], "001"/* No. */); // "/file/temp3/001/xx.jpg" // return information var isError = message. error; // determine whether the segment is uploaded successfully. var webPath = message. webFilePath; // return the web path var msg = message. message; // return the upload information var filePath = message. filePath; // reverse file path var isSuccess = message. error = false;

Code:

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 (Multi-File Upload is not supported currently) // ** Creation Time: /// ** modification time:-// *** Author: sunkaixuan // </summary> public class UploadFile {private ParamsModel Params; public Upl OadFile () {Params = new ParamsModel () {FileDirectory = "/upload", FileType = "Hangzhou", MaxSizeM = 10, PathSaveType = PathSaveType. dateTimeNow, IsRenameSameFile = true };}/// <summary> // file storage path (default:/upload) /// </summary> public void SetFileDirectory (string fileDirectory) {if (fileDirectory = null) {throw new ArgumentNullException ("fileDirectory");} va R 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 new file name (default: true) /// </summary> /// <param name = "isUseOldFileName"> true: original file name. false: The system generates a new file name. </param> public void SetIsUseOldFileName (bool isUseOldFileName) {Params. isUseOldFileName = IsUseOldFileName;} // <summary> // specifies the file type that can be uploaded. The file must be in lower case and separated by commas! * Indicates all (default value: .20.,.xls,.xlsx,.doc,.docx,.txt,.png,.jpg,.gif) /// </summary> public void SetFileType (string fileType) {Params. fileType = fileType;} // <summary> // The size (in MB) of the file to be uploaded. /// </summary> public void SetMaxSizeM (double maxSizeM) {Params. maxSizeM = maxSizeM;} // <summary> // rename a file of the same name? /// </Summary> /// <param name = "isRenameSameFile"> true: Rename, 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 the form File, create a subfolder // </summary> // <param name = "postFile"> HttpPostedFile </param> // <param name = "number"> NO. </param> /// <returns> </returns> public ResponseMessage Save (HttpPostedFile postFile, string number) {Params. pathSaveType = PathSaveType. code; _ Number = number; return CommonSave (postFile) ;}/// <summary> // Save the Form file, based on HttpPostedFile /// </summary> /// <param name = "postFile"> HttpPostedFile </p Aram> // <param name = "isRenameSameFile"> rename a file with the same name as true, false overwrites the original file </param> /// <param name = "fileName"> New file name </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;} // file name string fileName = Params. IsUseOldFileName? PostFile. fileName: DateTime. now. toString ("yyyyMMddhhmmssms") + Path. getExtension (postFile. fileName); // verify the format of this. checkingType (reval, postFile. fileName); // verify the size of this. checkSize (reval, postFile); if (reval. error) return reval; string webDir = string. empty; // obtain the storage directory var directory = this. getDirectory (ref webDir); var filePath = directory + fileName; if (System. IO. file. exists (filePath) {if (Params. I SRenameSameFile) {filePath = directory + DateTime. now. toString ("yyyyMMddhhssms") + "-" + fileName;} else {System. IO. file. delete (filePath) ;}// save the file 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 ;}} priv Ate void CheckSize (ResponseMessage message, HttpPostedFile PostFile) {if (PostFile. contentLength/1024.0/1024.0> Params. maxSizeM) {TryError (message, string. format ("sorry, the uploaded file is too large and cannot exceed {0} M! ", Params. maxSizeM ));}} /// <summary> /// obtain the relative path based on the 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> /// obtain the directory /// </summary> /// <returns> </returns> private string GetDirectory (ref string webDir) {var sever = HttpContext. current. server; // storage directory string directory = Params. fileDirectory; // directory Format string childDirectory = 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> // verify the file type) /// </summary> /// <param name = "fileName"> </param> private void CheckingType (ResponseMessage message, string fileName) {if (Params. fileType! = "*") {// Obtain the list of allowed upload types string [] typeList = Params. fileType. split (','); // obtain the upload file type (lower case) string type = Path. getExtension (fileName ). toLowerInvariant (); // verification type if (typeList. contains (type) = false) this. tryError (message, "the file type is invalid! ");}} /// <Summary> /// throw an error // </summary> /// <param name = "Msg"> </param> private void TryError (ResponseMessage message, string msg) {message. error = true; message. message = msg ;}# region models private class ParamsModel {// <summary> // file storage path /// </summary> public string FileDirectory {get; set ;} /// <summary> /// specifies the file type that can be uploaded. It must be separated by commas (,) and all must be in lower case! /// </Summary> public string FileType {get; set ;} /// <summary> /// the size of the file to be uploaded /// </summary> public double MaxSizeM {get; set ;} /// <summary> /// path storage type /// </summary> public PathSaveType {get; set ;} /// <summary> /// rename a file with the same name? /// </Summary> public bool IsRenameSameFile {get; set ;} /// <summary> /// whether to use the original file name /// </summary> public bool IsUseOldFileName {get; set ;}} /// <summary> /// path storage type /// </summary> public enum PathSaveType {/// <summary> /// create a storage directory Based on Time /// </summary> dateTimeNow = 0, /// <summary> /// create a storage directory by ID. // </summary> code = 1} private string _ Number {get; set ;} /// <summary> /// reverse return information /// </summary> public class ResponseMessage {// <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 ;} /// <summary> /// website path /// </summary> public string WebFilePath {get; set ;} /// <summary> /// get the 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.