C # code for uploading files

Source: Internet
Author: User

1<%@ WebHandler Language="C #"Class="UploadFile" %>  2 3 using System;  4 using System.Collections;  5 using System.Collections.Generic;  6 using System.Drawing;  7 using System.Drawing.Drawing2D;  8 using System.Threading; 9 using System.Web; Ten using SYSTEM.WEB.MVC; one using System.Web.Script.Serialization; Using System.IO;  Uploadhandler///<summary>///Uploadfile:ihttphandler 18//</summary> public class {19//File upload directory of the private string uploadfolder = "/userimages/"; 21//define the file extension that is allowed to be uploaded from the private string filety pes = "jpg,gif,jpeg,png,doc,pdf,html,htm"; 23//Maximum file size 1mb=1000000byte private int maxSize = 20000000;         The public void ProcessRequest (HttpContext context) is {uploaddata data = new Uploaddata (); 29 Context. Response.ContentType = "Text/plain"; httpfilecollection files = context. Request.Files; Try + {if (files). Count <= 0 | |              FILES[0] = = null) 35 {36   Returnerror (Context, "Please select a file. "); PNS} httppostedfile file = Files[0]; if (file. InputStream = = NULL | | File. Inputstream.length > MaxSize) returnerror (context, "Upload file size exceeds the limit. "); The string fileext = System.IO.Path.GetExtension (file. FileName). ToLower (); ArrayList filetypelist = Arraylist.adapter (Filetypes.split (', ')); if (String.IsNullOrEmpty (fileext) | | Array.indexof (Filetypes.split (', '), fileext.substring (1). ToLower ()) = =-1) returnerror (context, "The upload file name extension is not allowed. "); 51} 52 53//Add New file * * String fileName = Getdatetimeno (). ToString (); The string folderName = context. request.querystring["FolderName"]; Datename string = DateTime.Now.ToString ("Yyyy-mm-dd"); Dirpath String = context. Server.MapPath ("\\UserImages\\" + folderName + "\\ "+ datename +" \ \ "); if (!             Directory.Exists (Dirpath)) {directory.createdirectory (Dirpath); 61} 62 String path = context. Server.MapPath (Uploadfolder) + folderName + "\ \" + datename + "\ \"; Filefullname string = FileName + Fileext; String Savepath = path + filefullname; The file. SaveAs (Savepath); The image image = Image.FromFile (Savepath);                     FolderName ("Reports") ($ 74) Image img = Thumbnail (image, 188, 140); IMG. Save (path + "/s_" + filefullname); The image. Dispose (); ; "Activity": Bayi Image img2 = Thumbnail (image, 360, 270); Img2. Save (path + "/s_" + filefullname); The image. Dispose ();             86        Break "Activitybrend": "the image of Img3 = Thumbnail (image, 280, 266); Img3. Save (path + "/s_" + filefullname); The image. Dispose (); 94 break; "Releasecars": img4 image = Thumbnail (image, 280, 266); 98 IMG4. Save (path + "/s_" + filefullname), 101 image. Dispose (); 102 break;103 104}105 data. filename = datename + "/" + filename + fileext;106 data. FILEURL = Uploadfolder + folderName + "/" + Datename + "/" + FileName + fileext;107}108 catch (Exception E) 109 {data. Error = e.message;111}112 context. Response.Write (New JavaScriptSerializer (). Serialize (data)); 113 context. Response.End ();}115 DeleteFile (HttpContext context, String fiLename) 117 {118 String Delfilepath = context. Server.MapPath (fileName), 119 if (File.exists (Delfilepath)), {121 new FileInfo (Delfilepath). D         Elete (); 122}123}124 private void Returnerror (HttpContext context, string error) 126 {127 Uploaddata data = new Uploaddata (); Error = error;129 context. Response.AddHeader ("Content-type", "text/html; Charset=utf-8 "); Response.Write (New JavaScriptSerializer (). Serialize (data)); 131 context. Response.End ();}133 134 #region generated by datetime number 135//<summary>136//By Date number 137//</summar y>138//<param name= "num" > Number of digits (default 18 bit) </param>139//<returns> number </returns>140 Publi C long getdatetimeno (int num = $) 141 {142 if (num >) num = 20;143 string formatbase = "YyyyMMdd Hhmmssffffff "; 144 thread.sleep (1); 145 return long. Parse ((DateTime.Now. ToString (Formatbase)).  Substring (0, num)); 146}147//<summary>148//Generate number by date (after 4 seeds according to seed) 149//</summary>150// <param name= "Rand" > Seed </param>151//<param name= "num" > Number of digits (default 18-bit) </param>152//<retur         Ns> number </returns>153 public long getdatetimeno (int seed, int num =) 154 {155 Long result = 0;156 if (num >) num = 20;157 string formatbase = "Yyyymmddhhmmssffffff"; 158 string seedstr = Seed . ToString (). PadLeft (4, ' 0 '); 159 result = long. Parse ((DateTime.Now.ToString (formatbase)).     Substring (0, num-4) + seedstr), result;161}162 #endregion163 164 165 166 167//Shrink Picture 168 Public Image Thumbnail (image image, int width, int height) 169 {var newwidth = width;171 var newh eight = image. Height * Newwidth/image. width;172 173 if (Newheight < height) 174 {175//Resize with height instead176             Newwidth = image. Width * Height/image.  height;177 newheight = height;178}179-var tempimage = new Bitmap (newwidth, newheight); 181 182 using (var graphic = graphics.fromimage (tempimage)) 183 {184//Specifies a high-quality double three-time interpolation method. Perform pre-screening to ensure high-quality shrinkage. This mode produces the highest quality conversion image. 185 graphic. Interpolationmode = interpolationmode.high;186 187//Specifies high speed rendering 188 graphic. SmoothingMode = smoothingmode.highquality;189//graphic. Pixeloffsetmode = pixeloffsetmode.highquality;191 192//Linear quality setting 193 graphic. compositingquality = system.drawing.drawing2d.compositingquality.highquality;194 graphic. DrawImage (image, 0, 0, newwidth, newheight); 195}196 197 var x = (newwidth-width)/2;198 var y         = 0;199 var thumbnail = tempimage.clone (new Rectangle (x, y, width, height), tempimage.pixelformat); 200 201 Return thumbnail;202}203 204 public BooL IsReusable205 {206 get207 {208 return false;209}210}211}212 213 public cl UpLoadData214 {215///<summary>216//Error message 217//</summary>218 public string Error {SE T Get }219//<summary>220///File name 221//</summary>222 public string FileName {set; get;} 223//<summary>224///file path 225//</summary>226 public string FileUrl {set; get;} 227 228 public Uploaddata () 229 {. Error = string. empty;231 this. FileName = string. empty;232 this. FILEURL = string. empty;233}234}

C # code for uploading files

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.