Asp. NET file Upload Control Uploadify method of Use _ Practical skills

Source: Internet
Author: User
Tags file upload httpcontext

For the document came to say, there are many ways to implement, such as the traditional form, now popular flash mode, and even pure JS way, the reason for these ways to achieve file upload, I think the main reason is because the traditional upload for large file support is not enough, because it is a single thread synchronization mechanism, When large files are sent to the server via HTTP, the main thread of the server site has a greater impact, blocking, so, now a lot of upload control is asynchronous, multi-threaded way to achieve.

Today to introduce a file upload control, it is uploadify, it should be the flash of the asynchronous upload tool, for large file support is not bad, so I chose it.

Related API Introduction

uploader:uploadify.swf file relative path, the SWF file is a text browse button, click and Fade Open File dialog box, default: uploadify.swf.
Script: The relative path of the background handler. Default value: uploadify.php
Checkscript: Used to determine the relative path of a background handler that uploads selected files to the presence of the server
Filedataname: Sets a name, in the server handler according to the name to fetch the data of the uploaded file. Default is Filedata
Method: Submit to post or get defaults to post
Scriptaccess:flash script file access mode, if the local test is set to always, default value: Samedomain
Folder: The directory where the uploaded files are stored.
Queueid: ID of the file queue, which is the same as the ID of the div that holds the file queue.
Queuesizelimit: When multiple file generation is allowed, set the number of selected files, the default value: 999.
Multi: Multiple files can be uploaded when set to True.
Auto: Set to True when the file is selected directly uploaded, for false need to click the Upload button to upload.

Fileext: Sets the type of file that can be selected, in the format of: ' *.jpg;*.gif,*.png '.

Filedesc: This attribute value must be set to the Fileext property before it is valid to set the prompt text in the Select File dialog box, such as setting Filedesc as "Please select Image file".
SizeLimit: Size limit for uploading files.
Simuploadlimit: Allow simultaneous upload of the number of defaults: 1.
ButtonText: The text of the browse button, default: Browse.
BUTTONIMG: The path to the picture of the browse button.
Hidebutton: Set to True hides the picture of the browse button.
Rollover: A value of true and false, when set to true, has a reversal effect when the mouse is moved over the browse button.
Width: Sets the navigation button widths, the default value: 110.
Height: Sets the browse button heights, default value: 30.
Wmode: Set this as transparent to make the flash background file transparent for the browse button, and the Flash file will be placed at the top level of the page. Default value: Opaque.
CANCELIMG: Select the Close button icon on each file after file to the file queue

Structure diagram

HTML code

<div>
 <div class= "Inputdiv fl" >
 <input type= "text" name= "ImagePath" id= "ImagePath" style= " width:600px; " >
 
 </div>
 <div class= "fl" style= "position:relative" >
 <input id= "custom_file_uploadedu" type= "file" class= "btn"/> <a "href= javascript:$
 " (' #custom_ File_uploadedu '). Uploadifyupload () "> Upload </a>| 
 <a href= "javascript:$ (' #custom_file_uploadEdu '). Uploadifyclearqueue ()" > Cancel upload </a>
 </div>
 <div id= "displaymsg" ></div>
</div>

JS Code

<script type= "Text/ecmascript" > $ ("#custom_file_uploadEdu"). Uploadify ({' Uploader ': '/scripts/uploadify/ uploadify.swf ', ' script ': '/ashx/uploadfile.ashx ', ' cancelimg ': '/scripts/uploadify/uploadify-cancel.png ', ' folder ' : '/', ' queuesizelimit ': 1, ' simuploadlimit ': 1, ' sizelimit ': 1024 * 1024 * 5, ' multi ': false, ' auto ': false,/* if automatic
 Upload, the upload button will be useless/' fileext ': ' *.jpg;*.gif;*.jpeg;*.mp4 ', ' filedesc ': ' Please select image or video ', ' Queueid ': ' Filequeue ', ' width ': 110,
  ' Height ': ' buttontext ': ' Select ', ' wmode ': ' Opaque ', ' Hidebutton ': false, ' onselect ': function (event, ID, Fileobj) {
 $ ("#displayMsg"). html ("Upload ...");
  }, ' OnComplete ': function (event, Queueid, Fileobj, response, data) {var ary = response.split (' | ');
  if (ary[0] = = "0") {//Prompt error message alert (ary[1]);
   else {if (ary[0]== "1") {//uploaded URL $ ("#displayMsg"). HTML ("Upload succeeded") $ ("#ImagePath"). attr ("value", ary[1]); $ ("#ImagePath"). Remove ("img"). Next ("IMG"). Show (). attr ({"Style": "width:50px;height:50px;"," src ": ary[1]});
  else {//Exception Information alert (ary[1]);
}
  }
 }
 });

 </script>

Background handler (receive stream, write stream)

Namespace Webtest.ashx
{
 ///<summary>
 ///uploadfile Summary description
 ///</summary>
 Public Class Uploadfile:ihttphandler
 {public
 void ProcessRequest (HttpContext context)
 {context
  . Response.ContentType = "Text/plain";

  Context. Response.Write (New Uploadimpl (). Upload (context, Uploadtype.productimage, false));

 public bool IsReusable
 {
  get
  {return
  false;

}}}

Uploadimpl Class Code

Implementation of namespace EntityFrameworks.Application.Core.FileUpload {///<summary>///image upload function///</summary> publ IC class Uploadimpl {public Uploadimpl (ifileuploadsize fileuploadsize) {_fileuploadsize = fileuploadsize?? New Te
 Stfileuploadsize (); Uploadimpl (): this (null) {} #region Fields & consts static string Filehosturi = System.configuratio n.configurationmanager.appsettings["Filehosturi"]??

 HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority; Point point = new Point (0, 0);
 The image is intercepted from the coordinate point double wrate = 1, hrate = 1, setrate = 1;
 int newwidth = 0, newheight = 0;
 Ifileuploadsize _fileuploadsize; #endregion #region Image Scaling///<summary>///image scaling///</summary>///<param name= "file" > Zoom file </par am>///<param name= "width" > Width </param>///<param name= "height" > High </param>///<param name= "Isequalscale" > whether proportional scaling </param>///<param name= "nAme "> Zoom in after the address </param>///<returns></returns> bool Createthumbnail (httppostedfile file,
  ImageSize ImageSize, bool Isequalscale, string name) {Double width = (double) imagesize.width;

  Double height = (double) imagesize.height;; try {System.Drawing.Image Image = System.Drawing.Image.FromStream (file.
  InputStream); if (Isequalscale) {if (image). Height > height) {hrate = Height/image.
   Height; } if (image. Width > width) {wrate = Width/image.
   Width;
   } if (wrate!= 1 | | | hrate!= 1) {if (Wrate > hrate) {setrate = hrate;
   else {setrate = wrate; } newwidth = (int) (image.
   Width * setrate); Newheight = (int) (image.
   Height * setrate); if (height > newheight) {point.
   Y = Convert.ToInt32 (HEIGHT/2-NEWHEIGHT/2); } if (Width > newwidth) {point.
   X = Convert.ToInt32 (WIDTH/2-NEWWIDTH/2); } Bitmap bit = new Bitmap ((int) (width), (int) (HeigHT)); Rectangle r = new Rectangle (point. X, point. Y, (int) (image. Width * setrate), (int) (image.

  Height * setrate));
  Graphics g = graphics.fromimage (bit);
  G.clear (Color.White);


  G.drawimage (image, R);
  MemoryStream ms = new MemoryStream (); Bit.
  Save (MS, Imageformat.jpeg); byte[] bytes = Ms.
  ToArray (); String fileName = name + imagesize.tostring ()//renames the using for the scaled image (FileStream stream = new FileStream (FileName, filemode.c reate, FileAccess.Write)) {stream. Write (bytes, 0, bytes.
  Length); Bit.
  Dispose (); Ms.
  Dispose (); Image.
  Dispose ();
  return true;
  catch (Exception) {return false; }///<summary>///image Proportional scaling, the default filename does not change, overwriting the original file///</summary>///<param name= "file" ></param&gt
 ; <param name= "width" ></param>///<param name= "height" ></param>///<returns></  returns> bool Createthumbnail (httppostedfile file, ImageSize imagesize, string name) {return Createthumbnail (file, ImageSize, True, name); #endregion public String Upload (HttpContext context, Uploadtype type, bool Isscale) {ImageSize imagesize = _file

  Uploadsize.imagesizefortype[type]; httpfilecollection files = context.

  Request.Files; if (Files.
  Count = = 0) {throw new ArgumentNullException ("Please choose the file for upload."); String path = "/upload/" + type. ToString ();//relative path if (!
  Directory.Exists (path)) directory.createdirectory (path);

  Only take the 1th file var file = Files[0]; if (file!= null && file. ContentLength > 0) {try {string filename = context. request.form["FileName"]. Split ('. ')

   [0] + "_" + DateTime.Now.ToString ("yyyymmddhhssmm") + imagesize.tostring (); Local file system path string Savepath = Path.Combine (context.
   Server.MapPath (path), filename); File.
   SaveAs (Savepath);

   if (isscale) createthumbnail (file, ImageSize, Savepath);

   Returns the URI path string imageuri = Filehosturi + path + "/" + filename;
  Return "1|" + Imageuri;
}  catch (Exception ex) {return "0|" + ex.
  message;
 } return null;
 }

 }
}

Effect Chart:

For everyone to recommend a special topic for everyone to learn:"ASP." NET file Upload Summary "

The above is about ASP.net file Upload control uploadify The first part of the content of the introduction, then there are updates, I hope we do not miss.

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.