How to Use the ASP. NET File Upload control Uploadify, asp. netuploadify
There are many implementation methods for file upload, such as the traditional form method, the popular flash method, and even the pure JS method. These methods are used to upload files, I think the main reason is that traditional upload does not support large files because it is a single-thread synchronization mechanism. When large files are sent to the server through HTTP, the main thread of the server site has a large impact and will cause blocking. Therefore, many upload controls are implemented asynchronously and in multiple threads.
Today, we will introduce a file upload control, which is Uploadify, which should be a flash asynchronous upload tool with good support for large files. So I chose it.
Related API Introduction
Uploader: The relative path of the uploadify.swf file. This swf file is a button with a text BROWSE. After clicking it, it fades out the open file dialog box. Default Value: uploadify.swf.
Script: The relative path of the background processing program. Default Value: uploadify. php
CheckScript: used to determine whether the selected file to be uploaded is in the relative path of the background processing program on the server
FileDataName: Set a name based on the name in the server handler to obtain the data of the uploaded file. The default value is Filedata.
Method: The default submission method is Post or Get.
ScriptAccess: the access mode of the flash script file. If you set it to always in a local test, the default value is sameDomain.
Folder: directory where the uploaded files are stored.
QueueID: ID of the file queue, which is consistent with the ID of the div storing the file queue.
QueueSizeLimit: when multiple files are allowed to be generated, set the number of selected files. Default Value: 999.
Multi: When set to true, multiple files can be uploaded.
Auto: Set to true. When a file is selected, it is uploaded directly. If it is set to false, You need to click the upload button to upload the file.
FileExt: Set the file type that can be selected. The format is '*. jpg; *. gif, *. png '.
FileDesc: This attribute value is valid only after the fileExt attribute is set. It is used to set the prompt text in the Select File Dialog Box. For example, set fileDesc to "select Image File ",
SizeLimit: Specifies the size limit of the file to be uploaded.
SimUploadLimit: the number of simultaneous uploads allowed. Default Value: 1.
ButtonText: the text of the browser button. Default Value: BROWSE.
ButtonImg: Path of the image of the browser button.
HideButton: if it is set to true, the image of the Browse button is hidden.
Rolover: The values are true and false. If it is set to true, the result is reversed when you move the cursor over the Browse button.
Width: Set the width of the browser button. Default Value: 110.
Height: Set the height of the Browse button. Default Value: 30.
Wmode: If this parameter is set to transparent, the flash background file of the browser button is transparent, and the flash file is set to the top level of the page. Default Value: opaque.
CancelImg: select the close button icon for each file after the file is in the file queue.
Structure chart
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>
JS Code
<Script type = "text/ecmascript"> $ ("# custom_file_uploadEdu "). uploadify ({'upload': '/Scripts/Uploadify/uploadify.swf', 'script': '/ashx/UploadFile. ashx ', 'cancelim':'/Scripts/Uploadify/uploadify-cancel.png ', 'folder':'/', 'queuesizelimit': 1, 'simuploadlimit ': 1, 'sizelimit ': 1024*1024*5, 'Multi ': false, 'auto': false,/* If Automatic upload is performed, the upload button is useless */'fileext ':'*. jpg ;*. gif ;*. jpeg ;*. mp4 ', 'filedesc': 'select an image or video', 'queueid': 'filequeue', 'width': 110, 'height': 30, 'buttontext ': 'select', 'wmode': 'opaque ', 'hidemo': false, 'onselect': function (event, ID, fileObj) {$ ("# displayMsg" pai.html ("Uploading ...... ") ;}, 'oncomplete': function (event, queueId, fileObj, response, data) {var ary = response. split ('|'); if (ary [0] = "0") {// error message alert (ary [1]);} else {if (ary [0] = "1") {// The uploaded URL $ ("# displayMsg" successfully uploaded ") $ ("# 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 Processing Program (receiving stream, writing Stream)
Namespace WebTest. ashx {/// <summary> /// summary of UploadFile /// </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 code
Namespace EntityFrameworks. application. core. fileUpload {// <summary> // Implementation of the image upload function /// </summary> public class UploadImpl {public UploadImpl (IFileUploadSize fileUploadSize) {_ fileUploadSize = fileUploadSize ?? New TestFileUploadSize ();} public UploadImpl (): this (null) {}# region Fields & Consts static string FileHostUri = System. Configuration. ConfigurationManager. deleettings ["FileHostUri"]? HttpContext. current. request. url. scheme + ": //" + HttpContext. current. request. url. authority; Point point = new Point (0, 0); // capture the image 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"> file scaling </ param> /// <param name = "width"> width </param> /// <param name = "heig Ht "> height </param> /// <param name =" isw.scale "> proportional scaling </param> /// <param name =" name "> after scaling storage 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 (isEq UalScale) {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 Rectan Gle (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 (); // rename using (FileStream stream = new FileStream (fileName, FileMode. create, FileAcc Ess. write) {stream. write (bytes, 0, bytes. length);} bit. dispose (); ms. dispose (); image. dispose (); return true;} catch (Exception) {return false ;}/// <summary> // proportional scaling of the image. The default file name remains unchanged, overwrite the original file /// </summary> /// <param name = "file"> </param> /// <param name = "width"> </ param> /// <param name = "height"> </param> // <returns> </returns> bool CreateThumbnail (HttpPostedFile file, imageSize imageSize, st Ring name) {return CreateThumbnail (file, imageSize, true, name) ;}# endregion public string Upload (HttpContext context, UpLoadType, bool isScale) {ImageSize imageSize = _ fileUploadSize. imageSizeForType [type]; HttpFileCollection files = context. request. files; if (files. count = 0) {throw new ArgumentNullException ("please choose file for upload. ");} string path ="/upload/"+ type. toString (); // Relative path if (! Directory. Exists (path) Directory. CreateDirectory (path); // obtain only 1st files 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); // return URI path string ImageUri = FileHostUri + path + "/" + filename; return "1 |" + ImageUri;} catch (Exception ex) {return "0 |" + ex. message ;}} return null ;}}}
:
We recommend a special topic for you to learn:ASP. NET File Upload Summary
The above is the first part of the content about the ASP. NET File Upload control Uploadify. Next, there will be updates. I hope you will not miss them.
Articles you may be interested in:
- Code for file upload and deletion in asp.net
- Asp.net large file upload Control
- JQuery. uploadify
- How to Use uploadify, A File Upload Component in asp.net (c #) development (with progress bar)
- Use Fine Uploader + ASP. net mvc to upload ajax files [Sample Code]
- Implementation Method and idea of Asp. Net refreshing file upload and display progress bar
- Asp.net upload attachment example using jQuery Uploadify