Asp. NET implementation of Simple File upload class _ Practical skills

Source: Internet
Author: User

Call Method:

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 in a chronological directory
. Save (request.files["Fileupload1"]); "/file/temp3/2015/4/xx.jpg"
 
//File saves
var message2 = uf in numbered catalogs. 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:

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 UploadFile () {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 fi
      Ledirectory) {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= "Isuseo
      Ldfilename ">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>///allowed to upload how many sizes (units: M)///</summary> public void Setmaxsizem (double maxsizem)
    {params.maxsizem = Maxsizem;
    ///<summary>///Rename a file with the same name? </summary>///<param name= "IsrenAmesamefile ">true: Rename, false overwrite </param> public void Setisrenamesamefile (bool isrenamesamefile) {Para Ms.
    Isrenamesamefile = Isrenamesamefile; ///<summary>///Save the form file///</summary>///<param name= "Postfile" >httppostedfile&
      lt;/param>///<returns></returns> public responsemessage Save (Httppostedfile postfile) {
    Return Commonsave (Postfile); ///<summary>///Save form files, create subfolders based on numbers///</summary>///<param name= "Postfile" >ht
    tppostedfile</param>///<param name= "number" > Code </param>///<returns></returns> Public Responsemessage Save (httppostedfile postfile, string number) {Params.pathsavetype = Pathsavetype.code
      ;
      _number = number;
    Return Commonsave (Postfile); ///<summary>///Save the form file, according to Httppostedfile///</summary>///<param name= "Postfile" &G T Httppostedfile</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 Com
      Monsave (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); Verify 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.contentlen gth/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>///get relative path based on 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 Stri
      ng 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 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 (', '); Gets the upload file type (lowercase) String type = Path.getextension (fileName).
 
        Tolowerinvariant ();; Verify type if (Typelist.contains (type) = = False) this.
      Tryerror (Message, "File type illegal!");
    }///<summary>///throw 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 save path///</sum Mary> Public StrinG FileDirectory {get; set;}
      <summary>///allows uploading of file types, comma split, must all lowercase!
      </summary> public string FileType {get; set;}
      <summary>///allowed to upload how much size///</summary> public double maxsizem {get; set;}
      <summary>///Path Storage type///</summary> public pathsavetype pathsavetype {get; set;}
      <summary>///rename file with same name?
      </summary> public bool Isrenamesamefile {get; set;}
    <summary>///whether to use the original filename///</summary> public bool Isuseoldfilename {get; set;} ///<summary>///Path Storage type///</summary> public enum Pathsavetype {///<sum Mary>///Create a storage directory based on time///</summary> datetimenow = 0,///<summary>///based on ID number
 
    Way to create the storage directory///</summary> code = 1} private string _number {get; set;} ///<summary>///back Information///</summary> public class Responsemessage {///<summary>
      Upload error///</summary> public bool Error {get; set;}
      <summary>//////</summary> public string Messages {get; set;}
      <summary>///file path///</summary> public string FilePath {get; set;}
      <summary>///Web site path///</summary> public string Webfilepath {get; set;}
 
    <summary>///obtain filename///</summary> public string filename {get; set;}
 } #endregion}}

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.