context. Request.Files is not suitable for large files to operate, the following list is mainly for small file upload processing!
HTML Client section:
<formAction= "Upload.ashx"Method= "POST"enctype= "Multipart/form-data">Select File:<inputtype= "File"name= "File1" /><BR/> <inputtype= "Submit"value= "Upload" /> </form>
General handler server side:
Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain"; Httppostedfile file1= Context. request.files["file1"]; Helper.uploadfile (File1,"~/upload/");//here is the call to the corresponding methodContext. Response.Write ("OK");//Prompt Execution Success}
Encapsulation of the Code:
/// <summary> ///Upload Image/// </summary> /// <param name= "file" >to express a submitted file through a form</param> /// <param name= "Virpath" >the virtual path to save the file</param> Public Static voidUploadimg (httppostedfile file,stringVirpath) { if(file. ContentLength >1024x768*1024x768*4) { Throw NewException ("file cannot be greater than 4M"); } stringImgtype =path.getextension (file. FileName); if(imgtype!=". jpg"&&imgtype!=". JPEG")//limit the type of picture { Throw NewException ("please upload a JPG or JPEG image"); } using(Image img =bitmap.fromstream (file. InputStream)) {stringSavepath = HttpContext.Current.Server.MapPath (virpath+file. FileName); Img. Save (Savepath); } } /// <summary> ///Uploading Files/// </summary> /// <param name= "file" >to express a submitted file through a form</param> /// <param name= "Virpath" >the virtual path to save the file</param> Public Static voidUploadFile (httppostedfile file,stringVirpath) { if(file. ContentLength >1024x768*1024x768*6) { Throw NewException ("file cannot be greater than 6M"); } stringImgtype =path.getextension (file. FileName); //imgtype to restrict uploaded files if(Imgtype! =". zip"&& Imgtype! =". mp3") { Throw NewException ("only allow uploading zip, rar .... File"); } stringDirfullpath=HttpContext.Current.Server.MapPath (Virpath); if(! Directory.Exists (Dirfullpath))//If the folder does not exist, create the folder first{directory.createdirectory (Dirfullpath); } file. SaveAs (Dirfullpath+file. FileName); }
File Upload (ashx+form)