Use of upload component uploadify based on Mvc4+easyui development attachment

Source: Internet
Author: User
Tags jquery library
This article mainly introduces the Mvc4+easyui-based Web development framework of the attachment upload component uploadify Use, the need for friends can refer to the following

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 "></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>  <link href= "~/content/jquerytools/uploadify/uploadify.css" rel= "external nofollow" 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 action to add the upload and cancel the upload, as shown below.


 <tr> <th> <label for= "attachment_guid" > Attachment upload:</label> &LT;/TH&G            T <td> <p> <input class= "Easyui-validatebox" type= "hidden" id= "Atta Chment_guid "name=" Attachment_guid "/> <input id=" file_upload "name=" file_upload "type=" file "Multipl E= "multiple" > <a href= "javascript:void (0)" rel= "external nofollow" rel= "external nofollow" class= "eas Yui-linkbutton "id=" Btnupload "data-options=" plain:true,iconcls: ' Icon-save ' "onclick=" javascript: $ (' #fil E_upload '). Uploadify (' upload ', ' * ') "> Uploads </a> <a href=" javascript:void (0) "rel=" External nofollow "Rel=" external nofollow "class=" Easyui-linkbutton "id=" Btncancelupload "data-options=" PLAIN:TRUE,ICONCLS: '                Icon-cancel ' "onclick=" javascript: $ (' #file_upload '). Uploadify (' Cancel ', ' * ') ' > Cancel </a> <p id= "Filequeue" class= "Filequeue" ></p> <p id= "p_files" ></p> <br/> </p> </td> </tr>

The interface effect is initialized as follows:

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


<script type= "Text/javascript" > $ (function () {//Add interface for attachment Management $ (' #file_upload '). Uploadify ({' swf '): '/content/jquerytools/uploadify/uploadify.swf ',//flash file path ' buttontext ': ' Browse ',//button text ' Up Loader ': '/fileupload/upload ',//handling File Upload action ' Queueid ': ' Filequeue ',//queue ID ' Queuesi  Zelimit ': 10,//queue up to upload the number of files, default to 999 ' auto ': false,//Select whether the file is automatically uploaded, default to True ' multi ': True,//Whether it is a multi-select, the default is True ' removecompleted ': true,//whether to remove the sequence after completion, the default is True ' Filesizelimi T ': ' 10MB ',//single file size, 0 for unlimited, acceptable string value for KB,MB,GB units ' filetypedesc ': ' Image files ',//File Description ' fil Etypeexts ': ' *.gif; *.jpg; *.png;          *.bmp;*.tif;*.doc;*.xls;*.zip ',//upload file suffix filter ' onqueuecomplete ': function (event, data) {//All queue completion events Showupfiles ($ ("#Attachment_GUID"). Val (), "p_files"); After completion, update the list of uploaded files $.messager.alert ("Prompt", "Upload finished!") "); Prompt completion}, ' Onuploadstart ': function (file) {$ ("#file_upload"). Uploadify ("Settings", ' Formdat A ', {' folder ': ' Policy regulation ', ' GUID ': $ ("#Attachment_GUID"). Val ()}); Dynamic parameter}, ' 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 (Http Postedfilebase FileData, String guid, String folder) {if (fileData! = null) {try {C          ontrollerContext.HttpContext.Request.ContentEncoding = encoding.getencoding ("UTF-8");          ControllerContext.HttpContext.Response.ContentEncoding = encoding.getencoding ("UTF-8");          ControllerContext.HttpContext.Response.Charset = "UTF-8";          Save path after file upload string FilePath = Server.MapPath ("~/uploadfiles/");          Directoryutil.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 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 primary table record ID commonresult result = Bllfactory<fileupload>.          Instance.upload (info); if (!result. Success) {logtexthelper.error ("Upload file failed:" + 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.

The attachment editing and uploading interface is shown below.

The attachment information looks as follows:

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.