Home > Backend Development > C#.Net Tutorial > Develop the use of attachment upload component uploadify based on MVC4+EasyUI

Develop the use of attachment upload component uploadify based on MVC4+EasyUI

巴扎黑
Release: 2017-08-10 16:34:16
Original
2478 people have browsed it

This article mainly introduces the use of the attachment upload component uploadify of the Web development framework based on MVC4+EasyUI. Friends in need can refer to

1. Instructions for the upload component uploadify And script reference

Uploadify is a well-known upload plug-in for JQuery. Using Flash technology, Uploadify overcomes the limitations of the browser and controls the entire upload process, achieving no refresh on the client. File upload, thus realizing the upload progress control on the client, so you must first make sure that Adobe's Flash plug-in has been installed in the browser.

Uploadify currently has two versions, a free one based on Flash, and a paid version based on HTML5. We use the free version, and the current version is v3.2.1.

This component requires the support of the Jquery library. Under normal circumstances, you need to add the Jquery js library, as shown below


<script type="text/javascript" src="~/Scripts/jquery-2.0.3.min.js"></script>
Copy after login

But due to my Web development The framework is based on EasyUI. Generally, the relevant class library will be referenced at the beginning of the web page, which already includes the Jquery class library, as shown below.


 @*添加Jquery,EasyUI和easyUI的语言包的JS文件*@
  <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>
Copy after login

So we only need to add the Javascript class library (jquery.uploadify.js) and its style file (uploadify.css):


 @*添加对uploadify控件的支持*@
  @*<script type="text/javascript" src="~/Scripts/jquery-2.0.3.min.js"></script>*@
  
  
Copy after login

2. Use of the upload component uploadify in the Web interface

First we need to place two There are two controls, one for uploading, one for displaying the uploaded list, and the other is the button operation for adding upload and canceling upload, as shown below.


 <tr>
            <th>
              <label for="Attachment_GUID">附件上传:</label>
            </th>
            <td>              
              <p>
                <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)" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton" id="btnUpload" data-options="plain:true,iconCls:&#39;icon-save&#39;"
                  onclick="javascript: $(&#39;#file_upload&#39;).uploadify(&#39;upload&#39;, &#39;*&#39;)">上传</a>
                <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton" id="btnCancelUpload" data-options="plain:true,iconCls:&#39;icon-cancel&#39;"
                  onclick="javascript: $(&#39;#file_upload&#39;).uploadify(&#39;cancel&#39;, &#39;*&#39;)">取消</a>
                <p id="fileQueue" class="fileQueue"></p>
                <p id="p_files"></p>
                <br />
              </p>
            </td>
          </tr>
Copy after login

The interface effect initialization is as follows:

Of course, in the next step we need to add the corresponding file upload initialization The operation script code is as follows.


<script type="text/javascript">
    $(function () {
      //添加界面的附件管理
      $(&#39;#file_upload&#39;).uploadify({
        &#39;swf&#39;: &#39;/Content/JQueryTools/uploadify/uploadify.swf&#39;, //FLash文件路径
        &#39;buttonText&#39;: &#39;浏 览&#39;,                 //按钮文本
        &#39;uploader&#39;: &#39;/FileUpload/Upload&#39;,            //处理文件上传Action
        &#39;queueID&#39;: &#39;fileQueue&#39;,            //队列的ID
        &#39;queueSizeLimit&#39;: 10,             //队列最多可上传文件数量,默认为999
        &#39;auto&#39;: false,                 //选择文件后是否自动上传,默认为true
        &#39;multi&#39;: true,                 //是否为多选,默认为true
        &#39;removeCompleted&#39;: true,            //是否完成后移除序列,默认为true
        &#39;fileSizeLimit&#39;: &#39;10MB&#39;,            //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值
        &#39;fileTypeDesc&#39;: &#39;Image Files&#39;,         //文件描述
        &#39;fileTypeExts&#39;: &#39;*.gif; *.jpg; *.png; *.bmp;*.tif;*.doc;*.xls;*.zip&#39;, //上传的文件后缀过滤器
        &#39;onQueueComplete&#39;: function (event, data) {         //所有队列完成后事件
          ShowUpFiles($("#Attachment_GUID").val(), "p_files"); //完成后更新已上传的文件列表
          $.messager.alert("提示", "上传完毕!");                   //提示完成      
        },
        &#39;onUploadStart&#39; : function(file) {
          $("#file_upload").uploadify("settings", &#39;formData&#39;, { &#39;folder&#39;: &#39;政策法规&#39;, &#39;guid&#39;: $("#Attachment_GUID").val() }); //动态传参数
        },
        &#39;onUploadError&#39;: function (event, queueId, fileObj, errorObj) {
          //alert(errorObj.type + ":" + errorObj.info);
        }
      });
  </script>
Copy after login

In the above script, there are comments. You can understand the relevant attributes at a glance. If you don’t understand, you can also go to the official website to find out. It is worth noting that


&#39;uploader&#39;: &#39;/FileUpload/Upload&#39;
Copy after login

This line is to submit the file to the MVC Action for processing. We can handle it in the Upload of the controller FileUpload.

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


&#39;onQueueComplete&#39;: function (event, data) {
Copy after login

The last thing to note is that when uploading files, we need to dynamically obtain the values ​​​​of some elements on the interface and pass them as parameters, then we need Perform the following processing in the onUploadStart function.


$("#file_upload").uploadify("settings", &#39;formData&#39;, { &#39;folder&#39;: &#39;政策法规&#39;, &#39;guid&#39;: $("#Attachment_GUID").val() }); //动态传参数
Copy after login

3. The C# background processing code of upload component uploadify

is in the above transfer parameters , I used Chinese values. Under normal circumstances, this will result in Chinese garbled characters 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";
Copy after login

The complete background processing Action code of the controller FileUpload is 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";
          // 文件上传后的保存路径
          string filePath = Server.MapPath("~/UploadFiles/");
          DirectoryUtil.AssertDirExist(filePath);
          string fileName = Path.GetFileName(fileData.FileName);   //原始文件名称
          string fileExtension = Path.GetExtension(fileName);     //文件扩展名
          string saveName = Guid.NewGuid().ToString() + fileExtension; //保存文件名称
          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;//登录人
          //info.Owner_ID = OwerId;//所属主表记录ID
          CommonResult result = BLLFactory<FileUpload>.Instance.Upload(info);
          if (!result.Success)
          {
            LogTextHelper.Error("上传文件失败:" + 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;
    }
Copy after login

4. The interface display of the upload component uploadify in the Web development framework

The specific interface effect of the upload component in the Web development framework is as follows. The following picture is attached to the overall list. exhibit.

The attachment editing and uploading interface is as shown below.

The attachment information viewing effect is as follows:

The above is the detailed content of Develop the use of attachment upload component uploadify based on MVC4+EasyUI. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template