Mvc4+easyui-based Web development framework--the use of attachment upload component Uploadify

Source: Internet
Author: User
Tags httpcontext save file jquery library

A long time ago, when I was using ASP to develop some industry management system, I used this component as a file upload operation, in the essay "Web Development File Upload component Uploadify use " can be seen, How to use this component to upload files in ASP. The process of uploading files is mainly handled by using the ASHX General processing program. This article focuses on my web development framework, how to integrate this awesome file Upload component in a MVC4 environment.


1. Description of Upload component uploadify and script reference

Uploadify is a well-known JQuery upload plugin, the use of Flash technology, uploadify over the browser restrictions, control the entire upload process, to achieve a client-side file upload without refreshing, so that the implementation of the client upload progress control, so, You first need to make sure that the Adobe Flash plugin is already installed in your browser.
Uploadify currently has two versions, based on Flash is free, there is a HTML5-based pay version, we use the free version, the current version is v3.2.1.

This component requires the support of the jquery library, and in general, the JS Library of jquery needs to be added as follows

<script type= "Text/javascript" src= "~/scripts/jquery-2.0.3.min.js" ></script>

However, since my web development framework is based on Easyui, it is common to refer to the relevant class library at the beginning of the Web page, which already contains the JQuery class library, as shown below.

@* add JS files for Jquery,easyui and Easyui language packs *@ <script type= "Text/javascript" src= "~/content/jqueryeasyui/jquery.min.js" & gt;</script> <script type= "Text/javascript" src= "~/content/jqueryeasyui/jquery.easyui.min.js" ></ script> <script type= "Text/javascript" src= "~/content/jqueryeasyui/locale/easyui-lang-zh_cn.js" ></ Script>

So we just need to add the JavaScript class library (jquery.uploadify.js), plus his style file (UPLOADIFY.CSS):

@* add support for uploadify controls *@ @*<script type= "Text/javascript" src= "~/scripts/jquery-2.0.3.min.js" ></script>* @ <script type= "Text/javascript" src= "~/content/jquerytools/uploadify/jquery.uploadify.js" ></script> & Lt;link href= "~/content/jquerytools/uploadify/uploadify.css" rel= "stylesheet" type= "Text/css"/>
2, upload components uploadify in the use of the Web interface

First we need to place two controls in the HTML code, one for the upload, one for the control to display the uploaded list, and a button to add the upload and cancel the upload, as shown below.

<tr><th><label for= "Attachment_guid" > Accessories upload:</label></th><td>                              <div><input class= "Easyui-validatebox"  type= "hidden"  id= "Attachment_guid"  name= "Attachment_guid"  /><input id= "File_ Upload " name=" file_upload " type=" file " multiple=" multiple "><a href=" javascript:void ( 0) " class=" Easyui-linkbutton " id=" Btnupload " data-options=" plain:true,iconcls: ' Icon-save ' " onclick= "javascript: $ (' #file_upload '). Uploadify (' upload ',  ' * ')" > Upload </a><a href= " Javascript:void (0) " class=" Easyui-linkbutton " id=" Btncancelupload " data-options=" Plain:true, Iconcls: ' Icon-cancel ' "onclick=" javascript: $ (' #file_upload '). Uploadify (' Cancel ',  ' * ') ' > Cancel </a ><div id= "Filequeue"  class= "Filequeue" ></div><div id= "Div_files" ></div><br /></div> </td></tr>

The interface effect is initialized as follows:

650) this.width=650; "Src=" http://images.cnitblog.com/blog/8867/201309/28095848- Bfb360368f7d423294fb06b8c5a00c05.png "style=" border:0px; "/>

Of course, next we need to add the appropriate file upload initialization action script code, as shown below.

<script type= "Text/javascript" >$ (function  ()  {//Add the interface's attachment Management $ (' #file_upload '). Uploadify ({' SwF ':  '/content/jquerytools/uploadify/uploadify.swf ',   //flash file path ' buttontext ':  ' bangs     ',                                  //button text ' Uploader ':  '/fileupload/upload ',                        //processing file Upload action ' Queueid ':  ' fileQueue ',                          //Queue id ' queuesizelimit ': 10,                            //queue up to upload files, default is 999' Auto ': false,                                  // If the file is automatically uploaded after selecting it, the default is True ' multi ': true,                                   //is a multi-select, the default is True ' removecompleted ': true,                        //whether to remove sequence after completion, default to True ' Filesizelimit ':  ' 10MB ',                        //Single File size, 0 is unrestricted, can accept the string value of KB,MB,GB units such as ' Filetypedesc ':   ' Image files ',                  //File Description ' filetypeexts ':  ' *.gif; *.jpg; *.png; *.bmp;*.tif;*.doc;*.xls;*.zip ',   // Uploaded file suffix filter ' onqueuecomplete ': function  (event, data)  {                  //all queues complete after event Showupfiles ($ ("#Attachment_GUID") . Val (),  "Div_files");   //update the list of uploaded files after completion $.messager.alert ("Prompt",  "Upload complete! ");                                       //prompt complete            }, ' OnUploadStart '  :  function (file)  {$ ("#file_upload"). Uploadify ("Settings",  ' FormData ', {  ' folder ':   ' policy regulation ',  ' GUID ':  $ ("#Attachment_GUID"). Val ()  });  //dynamic Arguments}, ' Onuploaderror ':  function  (event, queueid, fileobj, Errorobj)  {//alert (errorobj.type +  ":"  + errorobj.info);}); </script>

In the above script, there are comments, a look at the relevant properties, do not understand can also go to the official website to find out. It is important to note that

' Uploader ': '/fileupload/upload '

This line is to submit the file to the MVC action to handle, we in the controller FileUpload upload processing.

In addition, after uploading the attachment, we need to update the interface to display the uploaded list, then we need to add the following function processing.

' Onqueuecomplete ': function (event, data) {

Finally, it is important to note that when uploading files, we need to dynamically get the values of some elements on the interface as parameters, so we need to do the following in the Onuploadstart function.

$ ("#file_upload"). Uploadify ("Settings", ' FormData ', {' folder ': ' Policy code ', ' GUID ': $ ("#Attachment_GUID"). Val ()}); Dynamic Transfer Parameters
3, upload the component uploadify C # background processing code

In the above pass parameter, I use the Chinese value, generally, this will get the Chinese garbled in the background, so we need to set its content format in the Controller's action function, as shown below.

ControllerContext.HttpContext.Request.ContentEncoding = encoding.getencoding ("UTF-8"); ControllerContext.HttpContext.Response.ContentEncoding = encoding.getencoding ("UTF-8"); ControllerContext.HttpContext.Response.Charset = "UTF-8";

The background processing action code for controller FileUpload is complete as follows:

Public class fileuploadcontroller : basecontroller{[acceptverbs (HttpVerbs.Post)]public  actionresult upload (httppostedfilebase filedata, string guid, string  folder) {if  (filedata != null) {try{controllercontext.httpcontext.request.contentencoding =  encoding.getencoding ("UTF-8"); Controllercontext.httpcontext.response.contentencoding = encoding.getencoding ("UTF-8"); controllercontext.httpcontext.response.charset =  "UTF-8";//  file after uploading the saved path String filepath  = server.mappath ("~/uploadfiles/");D irectoryutil.assertdirexist (filePath); string filename  = path.getfilename (filedata.filename);       //Original file name string  Fileextension = path.getextension (fileName);          // File extension String savename = guid.newguid (). ToString ()  + fileextension; //Save file name Fileuploadinfo&nbsP;info = new fileuploadinfo (); info. Filedata = readfilebytes (FileData);if  (info. Filedata != null) {info. Filesize = info. Filedata.length;} Info. Category = folder;info. Filename = filename;info. Fileextend = fileextension;info. Attachmentguid = guid;info. Addtime = datetime.now;info. editor = currentuser.name;//Login Person//info. owner_id = owerid;//belongs to the main table record idcommonresult result = bllfactory<fileupload>. Instance.upload (Info);if  (!result. Success) {Logtexthelper.error ("failed to upload file:"  + result. errormessage);} Return content (result. Success.tostring ());} catch  (Exception ex) {logtexthelper.error (ex); Return content ("false");}} Else{return content ("false");}} Private byte[] readfilebytes (Httppostedfilebase filedata) {byte[] data;using  (Stream  inputstream = filedata.inputstream) {memorystream memorystream = inputstream as memorystream;if  (memorystream == null) {memoryStream =  new memorystream (); Inputstream.copyto (MemoryStream);} Data = memorystream.toarray ();} Return data;}
4, upload components uploadify in the Web development framework of the interface display

The interface effect of the specific upload component in the Web development framework is shown below, and is the display of the attachments in the overall list.

650) this.width=650; "Src=" http://images.cnitblog.com/blog/8867/201309/28101433- F6346f1e7c334ed9b39a3e186075dc32.png "style=" border:0px; "/>

The attachment editing and uploading interface is shown below.

650) this.width=650; "Src=" http://images.cnitblog.com/blog/8867/201309/ 28101745-8f37633175144a16a8a16754cba8e863.png "style=" border:0px; "/>

The attachment information looks as follows:

650) this.width=650; "Src=" http://images.cnitblog.com/blog/8867/201309/ 28102300-8e9977496049497bb006a833eb5185cb.png "style=" border:0px; "/>



This article is from the "Wu Huacong blog" blog, make sure to keep this source http://wuhuacong.blog.51cto.com/1779896/1828911

Mvc4+easyui-based Web development framework--the use of attachment upload component Uploadify

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.