Use SWFUpload to upload images without refreshing images,

Source: Internet
Author: User
Tags file info

Use SWFUpload to upload images without refreshing images,

During project creation, A New Image Upload without refreshing is required. I have heard of SWFUpload before, so I want to use SWFUpload to upload images without refreshing, because my project belongs to ASP. so this article focuses on ASP. NET, I personally feel that the example is very clear. It is not difficult to refer to the document for development.

0. First download the swfUpload package. The downloaded package contains the samples folder and the demos folder under samples. Open the demos folder and you can see the structure shown in.

What we will use soon will include: the files in the swfupload directory and css are not recommended to avoid conflicts with the CSS written by ourselves, so that the page layout is completely messy. If you want to add Styles, you 'd better write them by yourself.

Open the applicationdemo.net directory and you will see this structure.

Open index.html and you can see this page.

Click Application Demo C # Under NET2.0

Add Resource reference

Resources to be referenced are included in the project (including files in the swfupload folder and resource files in the demo, handlers. js is the js file under the js directory in the demo)

First, familiarize yourself with the demo and include the page in the demo in the project.

On the Defaut. aspx page, use the swfUpload component to directly run the image without refreshing the new upload. Check the effect and get a rough idea of the basic process.

Modify the handlers. js File

The file structure of my project is probably like this.

The upload page for processing files is ImageUploadHandler. ashx. The page for obtaining the thumbnail is GetThumbHandler. ashx, Thumbnail. cs is a file in the App_Code folder in the demo. I personally think it is best to use a general processing program to process logic functions and not display pages. The handlers. js file must be modified to ensure that the page runs properly.

Final modified version Summary

Thumbnail

/// <Summary> /// Thumbnail /// </summary> public class Thumbnail {public Thumbnail (string id, byte [] data) {this. ID = id; this. data = data;} private string id; // <summary> // image id // </summary> public string ID {get {return this. id;} set {this. id = value ;}} private byte [] thumbnail_data; /// <summary> /// binary Data of the image /// </summary> public byte [] Data {get {return this. thumbnail_data;} set {this. thumbnail_data = value ;}} private string contentType; /// <summary> /// MIME type corresponding to the image /// </summary> public string ContentType {get {return contentType ;}set {contentType = value ;}}}

Html Demo

<! DOCTYPE html> 

ImageUploadHandler

/// <Summary> /// Image Upload processing /// </summary> public class ImageUploadHandler: IHttpHandler, IRequiresSessionState {// <summary> // record the log logger /// </summary> private static Common. logHelper logger = new Common. logHelper (typeof (ImageUploadHandler); public void ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; System. drawing. image thumbnail_image = null; System. drawin G. image original_image = null; System. drawing. bitmap final_image = null; System. drawing. graphics graphic = null; MemoryStream MS = null; try {// verify that the user is logged on and has the permission to upload if (context. session ["User"] = null) {context. response. write ("You are not authorized to upload images! "); Context. response. end (); return;} // obtain the uploaded file HttpPostedFile image_upload = context. request. files ["Filedata"]; // obtain the file extension string fileExt = System. IO. path. getExtension (image_upload.FileName ). toLower (); // verify whether the file extension meets the requirements and whether the image format is allowed if (fileExt! = ". Jpg" & fileExt! = ". Png ") {return;} // The current time string timeString = DateTime. now. toString ("yyyyMMddHHmmssfff"); // construct the image storage virtual path string path = "/Upload/" + timeString + fileExt; // save it to the context in the Session variable. session ["imgPath"] = path; // obtain and construct the physical path of the file to be uploaded. string serverPath = context. server. mapPath ("~ /"+ Path); // Save the image to the server image_upload.SaveAs (serverPath); // record the log logger. Debug (" the image has been uploaded successfully! "); # Region generates a thumbnail // gets the file stream original_image = System. drawing. image. fromStream (image_upload.InputStream); // calculate the width and height of the thumbnail based on the source image, and the scaling ratio ~~ Int width = original_image.Width; int height = original_image.Height; int target_width = 100; int target_height = 100; int new_width, new_height; float target_ratio = (float) target_width/(float) target_height; float image_ratio = (float) width/(float) height; if (target_ratio> image_ratio) {new_height = target_height; new_width = (int) Math. floor (image_ratio * (float) target_height);} else {new _ Height = (int) Math. Floor (float) target_width/image_ratio); new_width = target_width;} new_width = new_width> target_width? Target_width: new_width; new_height = new_height> target_height? Target_height: new_height; // create a thumbnail final_image = new System. drawing. bitmap (target_width, target_height); graphic = System. drawing. graphics. fromImage (final_image); graphic. fillRectangle (new System. drawing. solidBrush (System. drawing. color. black), new System. drawing. rectangle (0, 0, target_width, target_height); int paste_x = (target_width-new_width)/2; int paste_y = (target_height-new_height) /2; graphic. interpolationMode = System. drawing. drawing2D. interpolationMode. highQualityBicubic;/* new way * // graphic. drawImage (thumbnail_image, paste_x, paste_y, new_width, new_height); graphic. drawImage (original_image, paste_x, paste_y, new_width, new_height); // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo) MS = new MemoryStream (); // Save the thumbnail to the memory stream final_image.Save (MS, System. drawing. imaging. imageFormat. png); # endregion // create Thumbnail object Thumbnail thumb = new Thumbnail (timeString, ms. getBuffer (); // Save the thumbnail to the Session. You can also save it as a file and save it as the context of the image. session ["file_info"] = thumb; // The operation is successful. The HTTP status code is set to 200 context. response. statusCode = 200; // id of the output thumbnail, which must be context when generating the thumbnail. response. write (thumb. ID);} catch (Exception ex) {// an Exception occurs. 500 is returned and an internal server error occurs. Context. Response. StatusCode = 500; // record the Error log logger. Error (ex);} finally {// release the resource if (final_image! = Null) final_image.Dispose (); if (graphic! = Null) graphic. Dispose (); if (original_image! = Null) original_image.Dispose (); if (thumbnail_image! = Null) thumbnail_image.Dispose (); if (MS! = Null) ms. Close (); context. Response. End () ;}} public bool IsReusable {get {return false ;}}}

GetThumbHandler

/// <Summary> /// obtain the thumbnail /// </summary> public class GetThumbHandler: IHttpHandler, IRequiresSessionState {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/plain"; // obtain the thumbnail id string id = context. request. queryString ["id"]; // if (String. isNullOrEmpty (id) {context. response. status Code = 404; context. response. write ("Not Found"); context. response. end (); return;} // obtain the Thumbnail file Thumbnail thumb = context from the Session. session ["file_info"] as Thumbnail; // determine whether the id is consistent if (thumb. ID = id) {// reset the response MIME type context. response. contentType = "image/png"; // output the binary stream information context. response. binaryWrite (thumb. data); // end of the output context. response. end (); return;} // the corresponding image is not found, and 404 context is returned. response. status Code = 404; context. response. write ("Not Found"); context. response. end () ;}public bool IsReusable {get {return false ;}}}

Handlers. js File

Function fileQueueError (file, errorCode, message) {try {var imageName = "error.gif"; var errorName = ""; if (errorCode = SWFUpload. errorCode_QUEUE_LIMIT_EXCEEDED) {errorName = "too many files are uploaded! ";} If (errorName! = "") {Alert (errorName); return;} switch (errorCode) {case SWFUpload. QUEUE_ERROR.ZERO_BYTE_FILE: imageName = "zerobyte.gif"; break; case SWFUpload. QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: imageName = "toobig.gif"; break; case SWFUpload. QUEUE_ERROR.ZERO_BYTE_FILE: case SWFUpload. QUEUE_ERROR.INVALID_FILETYPE: default: alert (message); break;} // Add an image. Note the path addImage ("/swfupload/images/" + imageName);} c Atch (ex) {this. debug (ex) ;}} function fileDialogComplete (numFilesSelected, numFilesQueued) {try {if (numFilesQueued> 0) {this. startUpload () ;}} catch (ex) {this. debug (ex) ;}} function uploadProgress (file, bytesLoaded) {try {var percent = Math. ceil (bytesLoaded/file. size) * 100); var progress = new FileProgress (file, this. customSettings. upload_target); progress. setProgress (percent); if (p Ercent = 100) {progress. setStatus ("creating thumbnail... "); progress. toggleCancel (false, this);} else {progress. setStatus ("Uploading... "); progress. toggleCancel (true, this) ;}} catch (ex) {this. debug (ex) ;}} function uploadSuccess (file, serverData) {try {// Add a thumbnail ~~~ // Modify here to set the page addImage ("/Handlers/GetThumbHandler. ashx? Id = "+ serverData); var progress = new FileProgress (file, this. customSettings. upload_target); progress. setStatus (" thumbnail created successfully! "); Progress. toggleCancel (false);} catch (ex) {this. debug (ex) ;}} function uploadComplete (file) {try {/* I want the next upload to continue automatically so I'll call startUpload here */if (this. getStats (). files_queued> 0) {this. startUpload ();} else {var progress = new FileProgress (file, this. customSettings. upload_target); progress. setComplete (); progress. setStatus ("image uploaded successfully"); progress. toggl ECancel (false) ;}} catch (ex) {this. debug (ex) ;}} function uploadError (file, errorCode, message) {var imageName = "error.gif"; var progress; try {switch (errorCode) {case SWFUpload. UPLOAD_ERROR.FILE_CANCELLED: try {progress = new FileProgress (file, this. customSettings. upload_target); progress. setCancelled (); progress. setStatus ("the upload operation is canceled"); progress. toggleCancel (false);} catch (ex1) {this. deb Ug (ex1);} break; case SWFUpload. UPLOAD_ERROR.UPLOAD_STOPPED: try {progress = new FileProgress (file, this. customSettings. upload_target); progress. setCancelled (); progress. setStatus ("Upload stopped! "); Progress. toggleCancel (true);} catch (ex2) {this. debug (ex2);} case SWFUpload. UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: imageName = "uploadlimit.gif"; break; default: alert (message); break;} addImage ("/swfupload/images/" + imageName);} catch (ex3) {this. debug (ex3) ;}} function addImage (src) {var newImg = document. createElement ("img"); newImg. style. margin = "5px"; document. getElementById ("thumbnai Ls "). appendChild (newImg); if (newImg. filters) {try {newImg. filters. item ("DXImageTransform. microsoft. alpha "). opacity = 0;} catch (e) {// If it is not set initially, the browser will throw an error. this will set it if it is not set yet. newImg. style. filter = 'progid: DXImageTransform. microsoft. alpha (opacity = '+ 0 +') ';} else {newImg. style. opacity = 0;} newImg. onload = function () {fadeIn (NewImg, 0) ;}; newImg. src = src;} function fadeIn (element, opacity) {var performanceopacityby = 5; var rate = 30; // 15 fps if (opacity <100) {opacity + = performanceopacityby; if (opacity> 100) {opacity = 100;} if (element. filters) {try {element. filters. item ("DXImageTransform. microsoft. alpha "). opacity = opacity;} catch (e) {// If it is not set initially, the browser will throw an error. this will s Et it if it is not set yet. element. style. filter = 'progid: DXImageTransform. microsoft. alpha (opacity = '+ opacity +') ';} else {element. style. opacity = opacity/100; }}if (opacity <100) {setTimeout (function () {fadeIn (element, opacity) ;}, rate );}} /*************************************** * ***** FileProgress Object * Control object for displaying file info ************************** ****** * **********/Function FileProgress (file, targetID) {this. fileProgressID = "divFileProgress"; this. fileProgressWrapper = document. getElementById (this. fileProgressID); if (! This. fileProgressWrapper) {this. fileProgressWrapper = document. createElement ("div"); this. fileProgressWrapper. className = "progressWrapper"; this. fileProgressWrapper. id = this. fileProgressID; this. fileProgressElement = document. createElement ("div"); this. fileProgressElement. className = "progressContainer"; var progressCancel = document. createElement ("a"); progressCancel. className = "progressCancel "; ProgressCancel. href = "#"; progressCancel. style. visibility = "hidden"; progressCancel. appendChild (document. createTextNode (""); var progressText = document. createElement ("div"); progressText. className = "progressName"; progressText. appendChild (document. createTextNode (file. name); var progressBar = document. createElement ("div"); progressBar. className = "progressBarInProgress"; var progressStatu S = document. createElement ("div"); progressStatus. className = "progressBarStatus"; progressStatus. innerHTML = ""; this. fileProgressElement. appendChild (progressCancel); this. fileProgressElement. appendChild (progressText); this. fileProgressElement. appendChild (progressStatus); this. fileProgressElement. appendChild (progressBar); this. fileProgressWrapper. appendChild (this. fileProgressElement); document. g EtElementById (targetID ). appendChild (this. fileProgressWrapper); fadeIn (this. fileProgressWrapper, 0);} else {this. fileProgressElement = this. fileProgressWrapper. firstChild; this. fileProgressElement. childNodes [1]. firstChild. nodeValue = file. name;} this. height = this. fileProgressWrapper. offsetHeight;} FileProgress. prototype. setProgress = function (percentage) {this. fileProgressElement. className =" ProgressContainer green "; this. fileProgressElement. childNodes [3]. className = "progressBarInProgress"; this. fileProgressElement. childNodes [3]. style. width = percentage + "%" ;}; FileProgress. prototype. setComplete = function () {this. fileProgressElement. className = "progressContainer blue"; this. fileProgressElement. childNodes [3]. className = "progressBarComplete"; this. fileProgressElement. childNodes [3]. Style. width = "" ;}; FileProgress. prototype. setError = function () {this. fileProgressElement. className = "progressContainer red"; this. fileProgressElement. childNodes [3]. className = "progressBarError"; this. fileProgressElement. childNodes [3]. style. width = "" ;}; FileProgress. prototype. setCancelled = function () {this. fileProgressElement. className = "progressContainer"; this. fileProgressElement. childN Odes [3]. className = "progressBarError"; this. fileProgressElement. childNodes [3]. style. width = "" ;}; FileProgress. prototype. setStatus = function (status) {this. fileProgressElement. childNodes [2]. innerHTML = status ;}; FileProgress. prototype. toggleCancel = function (show, swfuploadInstance) {this. fileProgressElement. childNodes [0]. style. visibility = show? "Visible": "hidden"; if (swfuploadInstance) {var fileID = this. fileProgressID; this. fileProgressElement. childNodes [0]. onclick = function () {swfuploadInstance. cancelUpload (fileID); return false ;};}};

The above is all the content of this article. I hope it will be helpful for you to learn about asp.net.

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.