趁着近段的空闲时间,开发任务不是很重,就一直想把以前在仓促时间里所写的多文件上传功能改一下,在网上找了很多例子,觉得uploadify还可以,就想用它来试试。实现自己想要的功能。根据官网的开发文档,同时借鉴别人的经验,经过断断续续的修改(中间一直被安排其它事),把uploadify默认的样式改,同时把共性都封装了一下,最终完工了。

1.在_Layout.cshtml 页面中引入js文件和CSS文件:

  1. @*-------上传文件--------*@
  2. <link href="@Url.Content("~/Scripts/uploadify/css/uploadify.css")" rel="stylesheet" />
  3. <script src="@Url.Content("~/Scripts/JSScript/upload.js")"></script>
  4. <script src="@Url.Content("~/Scripts/uploadify/jquery.uploadify.min.js")"></script>
  5. <script src="@Url.Content("~/Scripts/jquery-1.7..min.js")" type="text/javascript"></script>

引入文件

2.我把每个页面都用到的方法封装在upload.js文件里,同时对各个相关的属性都作了解释(最主要的是 'swf': '/Scripts/uploadify/uploadify.swf'这个的路径要正确):

  1. function upload(config) {
  2. $("#" + config.id).uploadify({
  3. 'method': config.method ? config.method : 'post',//默认是’post’,可以设置为’get’
  4. 'formData': config.formData,
  5. 'swf': '/Scripts/uploadify/uploadify.swf', //关键的路径要正确
  6. 'uploader': '/HanNeng/Upload',
  7. 'buttonClass': config.buttonClass ? config.buttonClass : null, //额外增加的上传按钮样式类型
  8. 'buttonImage': config.buttonImage ? config.buttonImage : null, //按钮的背景图片
  9. 'buttonText': config.buttonText ? config.buttonText : '选择文件',//按钮显示的文字
  10. 'auto': config.auto ? config.auto : true, //选择文件后是否自动上传,默认是true,为自动上传
  11. 'height': config.width ? config.width : , //按钮的高度
  12. 'width': config.width ? config.width : , //按钮的宽度
  13. 'fileTypeDesc': config.fileTypeDesc, //文件类型的说明
  14. 'fileTypeExts': config.fileTypeExts, //指定允许上传的文件类型,默认*.*
  15. 'fileSizeLimit': config.fileSizeLimit, //上传文件大小限制,默认单位是KB,若需要限制大小在100KB以内, 可设置该属性为:‘100KB’
  16. 'removeTimeout': , //上传完成后的进度条的显示时间
  17. 'queueSizeLimit': config.queueSizeLimit, //上传队列长度限制,一次最多可上传多少个文件
  18. 'overrideEvents': ['onDialogClose', 'onUploadSuccess', 'onUploadError', 'onSelectError'], //不弹出默认的提示信息
  19. 'onSWFReady': config.sfdisable == true ? uploadify_onSWFReady : null, //如果有disable参数且为true时,就禁用掉上传功能
  20. 'onUploadStart': function (file) { //在一个文件开始上传之前触发。
  21. $("#" + config.id).uploadify("settings", config.formKey, config.formData);
  22. },
  23. 'onSelect': uploadify_onSelect, //选择文件后触发
  24. 'onSelectError': uploadify_onSelectError, //选择文件后出错时触发
  25. 'onUploadError': uploadify_onUploadError,//上传文件失败触发
  26. 'onUploadSuccess': uploadify_onUploadSuccess //在每一个文件上传成功后触发
  27. });
  28. }
  29.  
  30. //选择文件错误调用的方法
  31. var uploadify_onSelectError = function (file, errorCode, errorMsg) {
  32. var msgText = "上传失败,原因:\n\n";
  33. switch (errorCode) {
  34. case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
  35. msgText += " 每次上传的文件数量最多只可上传 " + this.settings.queueSizeLimit + "个文件!\n";
  36. break;
  37. case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
  38. msgText += " 文件 【" + file.name + "】 大小超过系统限制的( " + this.settings.fileSizeLimit + " )大小!\n";
  39. break;
  40. case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
  41. msgText += " 文件 【" + file.name + "】 大小为0,不可上传!\n";
  42. break;
  43. case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
  44. msgText += " 所选文件 【" + file.name + "】 的格式不正确,仅限上传(" + this.settings.fileTypeExts + ")的文件格式!\n";
  45. break;
  46. default:
  47. msgText += "错误代码:" + errorCode + "\n" + errorMsg;
  48. }
  49. art.dialog.alert(msgText);
  50. }
  51.  
  52. //文件上传错误调用的方法
  53. var uploadify_onUploadError = function (file, errorCode, errorMsg, errorString) {
  54. // 手工取消不弹出提示
  55. if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED
  56. || errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) {
  57. return;
  58. }
  59. var msgText = "上传失败\n\n";
  60. switch (errorCode) {
  61. case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
  62. msgText += " HTTP 错误\n" + errorMsg;
  63. break;
  64. case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
  65. msgText += " 上传文件 【" + file.name + "】 丢失,请重新上传!\n";
  66. break;
  67. case SWFUpload.UPLOAD_ERROR.IO_ERROR:
  68. msgText += " IO错误!\n";
  69. break;
  70. case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
  71. msgText += " 安全性错误\n" + errorMsg;
  72. break;
  73. case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
  74. msgText += " 每次最多上传 " + this.settings.uploadLimit + "个!\n";
  75. break;
  76. case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
  77. msgText += errorMsg;
  78. break;
  79. case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND:
  80. msgText += " 找不到指定文件,请重新操作!\n";
  81. break;
  82. case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
  83. msgText += "参数错误!\n";
  84. break;
  85. default:
  86. msgText += "文件:【" + file.name + "】\n错误码:" + errorCode + "\n"
  87. + errorMsg + "\n" + errorString;
  88. }
  89. art.dialog.alert(msgText);
  90. return parameters;
  91. }
  92.  
  93. //选择文件调用的方法
  94. var uploadify_onSelect = function () {
  95.  
  96. }
  97.  
  98. //上传成功后调用的方法
  99. var uploadify_onUploadSuccess = function (file, data, response) {
  100. var innerHtml = "";
  101. if (response) {
  102. var json = (new Function("", "return " + data))();
  103. innerHtml = "<li style=\"list-style: disc\">"
  104. + "<a style='color:#C51616' href='/HanNeng/DownFile?filePath=" + json.filePath + "&fileName=" + file.name + "&fileId=" + json.aID + "&backUrl=" + json.backUrl + "&url=" + json.url;
  105. if (json.urlID != "") {
  106. innerHtml += "?id=" + json.urlID;
  107. }
  108. innerHtml += "'>" + file.name + "</a>" + "<a style='margin-left: 10px;' href='javascript:void()' name='deleteImg' curid='" + json.aID + "' onclick=\"DeleteFile(this)\">"
  109. + "<img src='/Content/images/delete.png' /></a></li>";
  110.  
  111. //当上传的文档为课题的相关文档时,上传成功后作特殊处理
  112. if (json.attType.indexOf("KT") >= ) {
  113. $.ajax({
  114. type: 'POST',
  115. url: '/Subject/SubjectUploadDoc',
  116. dataType: 'json',
  117. data: { guid: json.guid, atttype: json.attType },
  118. success: function (data) {
  119. if (data.isok) {
  120. }
  121. }
  122. });
  123. }
  124. } else {
  125. innerHtml = "<div>该附件上传失败,请重新上传</div>";
  126. }
  127. $("#filename").html($("#filename").html() + innerHtml);
  128. }
  129.  
  130. //检测FLASH失败调用
  131. var uploadify_onFallback = function () {
  132. art.dialog.alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
  133. }
  134.  
  135. //加载完毕后,禁用uploadify时触发(通过disable方法)
  136. var uploadify_onSWFReady = function () {
  137. $('#file_upload').uploadify('disable', true);
  138. $(".uploadify-button-text").css("color", "#999");
  139. }

upload.js

3.MVC里控制器Controller的上传代码,并插入数据表中('uploader'这个引用到),在return Json()返回自己想要的参数,之后在上传成功后,在uploadify_onUploadSuccess方法里获取传过来的参数:

  1. #region uploadify上传文件方法
  2. [AcceptVerbs(HttpVerbs.Post)]
  3. public JsonResult Upload(HttpPostedFileBase fileData)
  4. {
  5. HanNeng.Common.UpLoadHelper upload = new HanNeng.Common.UpLoadHelper();
  6. string guid = HttpContext.Request.Form["guid"];
  7. string attType = HttpContext.Request.Form["attType"];
  8. string strUrl = HttpContext.Request.Form["url"];
  9. string strUrlID = HttpContext.Request.Form["urlID"];
  10. string backUrl = HttpContext.Request.Form["backUrl"];
  11. int i = ;
  12. int aid = ;
  13. bool istrue = false;
  14. if (fileData != null)
  15. {
  16. try
  17. {
  18. //文件上传后的保存路径
  19. string filePath = upload.FilePath;//文件保存的目录
  20. if (!Directory.Exists(filePath))
  21. Directory.CreateDirectory(filePath); //如果不存在UploadFile文件夹,则创建UploadFile文件夹
  22.  
  23. upload.FileName = System.IO.Path.GetFileName(fileData.FileName); //得到文件名字
  24. upload.FileWithoutName = System.IO.Path.GetFileNameWithoutExtension(fileData.FileName); //不含有扩展名
  25. upload.FileSize = fileData.ContentLength; //得到文件大小
  26. upload.FileExt = upload.GetExt(fileData.FileName);//得到文件扩展名
  27. upload.Category = fileData.ContentType; //得到文件输出类型
  28. upload.FileNewName = upload.GetFileName(upload.FileExt);
  29.  
  30. //存入文件
  31. fileData.SaveAs(filePath + upload.FileNewName);//保存文件到文件夹中
  32. string fileName = Path.GetFileName(fileData.FileName);// 原始文件名称
  33. string fileExtension = Path.GetExtension(fileName); // 文件扩展名
  34.  
  35. fileData.SaveAs(filePath + upload.FileNewName);
  36. string path = "/UploadFile/" + System.IO.Path.GetFileName(upload.FileNewName);
  37.  
  38. Model.Attachment att = new Model.Attachment();
  39. att.AttachmentID = System.Guid.NewGuid().ToString("D");
  40. att.FileName = upload.FileName;
  41. att.FileLogicName = upload.FileNewName;
  42. att.AttachmentType = attType;
  43. att.FID = guid;
  44. att.FilePath = path;
  45. att.FileSize = upload.FileSize;
  46. att.FileExtension = upload.FileExt;
  47. att.CreateUserID = Identity.UserID;
  48. att.CreateTime = DateTime.Now;
  49. att.Category = upload.Category;
  50. att.States = ;
  51. att.Summary = (i + ).ToString(); //排序
  52. istrue = new BLL.Attachment().Add(att) > ;
  53. if (istrue)
  54. {
  55. Model.Attachment matt = new BLL.Attachment().GetModel("AttachmentID", att.AttachmentID);
  56. if (matt != null)
  57. aid = matt.AttachmentAutoID;
  58. }
  59.  
  60. return Json(new
  61. {
  62. Success = true,
  63. fileName = att.FileName,
  64. SaveName = att.FileLogicName,
  65. attType = att.AttachmentType,
  66. filePath = att.FilePath,
  67. guid = att.FID,
  68. aID = aid,
  69. url = strUrl,
  70. urlID = strUrlID,
  71. backUrl = backUrl
  72. }, JsonRequestBehavior.AllowGet);
  73. }
  74. catch (Exception ex)
  75. {
  76. return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);
  77. }
  78. }
  79. else
  80. return Json(new { Success = false, Message = "请选择要上传的文件!" }, JsonRequestBehavior.AllowGet);
  81. }
  82. #endregion

Upload方法

4.删除已上传文件的方法:

  1. #region 无刷新删除上传的附件
  2. public JsonResult DeleteFile(int aID)
  3. {
  4. bool isOk = false;
  5. if (aID > )
  6. {
  7. Model.Attachment att = new BLL.Attachment().GetModel(aID);
  8. if (att != null)
  9. {
  10. isOk = new BLL.Attachment().Delete(aID);
  11. //将文件夹里的文件也一起删除
  12. if (System.IO.Directory.Exists(Request.MapPath("~/UploadFile/")))
  13. {
  14. if (System.IO.File.Exists(Request.MapPath("~/UploadFile/" + att.FileLogicName)))
  15. {
  16. System.IO.File.Delete(Request.MapPath("~/UploadFile/" + att.FileLogicName));
  17. }
  18. }
  19. }
  20. }
  21. return Json(new { success = isOk });
  22. }
  23. #endregion

DeleteFile方法

5.下载文件的方法

  1. #region 下载文件-DownFile
  2. /// <summary>
  3. /// 下载文件
  4. /// </summary>
  5. /// <param name="filePath">文件路径</param>
  6. /// <param name="fileName">文件名</param>
  7. /// <param name="fileId">下载文件自增id</param>
  8. /// <param name="url">下载失败返回界面url</param>
  9. /// <returns></returns>
  10. public ActionResult DownFile(string filePath, string fileName, string fileId, string url, string backUrl, string r = null)
  11. {
  12.  
  13. string strurl = "";
  14. if (url != null)
  15. strurl = url;
  16. if (r != null)
  17. strurl = url + "&r=" + r;
  18. if (!string.IsNullOrEmpty(backUrl))
  19. {
  20. strurl = strurl.Contains("?") ? strurl + "&backUrl=" + Url.Encode(backUrl) : strurl + "?backUrl=" + Url.Encode(backUrl);
  21. }
  22. if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(fileId))
  23. {
  24. return ShowRedirectMessage("下载失败", url != null ? strurl : "/Student/TableList");
  25. }
  26. //绝对路径
  27. filePath = Server.MapPath(filePath);
  28. if (!System.IO.File.Exists(filePath))
  29. {
  30. new BLL.Attachment().Delete(Convert.ToInt32(fileId));
  31. return ShowRedirectMessage("下载的文件不存在", url != null ? strurl : "/Student/TableList");
  32. }
  33. FileStream fs = new FileStream(filePath, FileMode.Open);
  34. byte[] bytes = new byte[(int)fs.Length];
  35. fs.Read(bytes, , bytes.Length);//读取文件
  36. fs.Close();
  37. Response.Charset = "UTF-8";
  38. Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
  39. Response.ContentType = "application/octet-stream";//以二进制流输出给浏览器
  40. //attachment:作为附件下载 inline:直接打开
  41. Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));
  42. Response.BinaryWrite(bytes);
  43. Response.End();
  44. return new EmptyResult();
  45. }
  46. #endregion
  47.  
  48. #region 获取附件列表 GetProFile
  49. /// <summary>
  50. /// 获取附件列表
  51. /// </summary>
  52. /// <param name="guid"></param>
  53. /// <param name="attType"></param>
  54. /// <param name="a"></param>
  55. /// <returns></returns>
  56. public static List<MvcHtmlString> GetProFile(string guid, string attType, string a = null, string url = null, string backUrl = null)
  57. {
  58. List<Model.Attachment> M_Att = new BLL.Attachment().GetModelList(guid, attType);
  59. List<MvcHtmlString> list = new List<MvcHtmlString>();
  60. string str = "";
  61. foreach (var item in M_Att)
  62. {
  63. str = "<a style='color:#C51616' href='/HanNeng/DownFile?filePath=" + item.FilePath + "&fileName=" + item.FileName + "&fileId=" + item.AttachmentAutoID + "&url=" + url + "&backUrl=" + backUrl + "'>" + item.FileName + "</a>";
  64. if (a != null)
  65. {
  66. str += "<a style='margin-left: 10px;' href='javascript:void()' name='deleteImg' curid='" + item.AttachmentAutoID + "' onclick=\"DeleteFile(this)\"><img src='/Content/images/delete.png' /></a>";
  67. }
  68. list.Add(new MvcHtmlString(str));
  69. }
  70. return list;
  71. }
  72. #endregion

下载文件

6.在页面上的调用,设置一个全局变量var disable = false;是因为有些页面要根据权限禁用掉上传的功能。当全部加载完毕调用的是uploadify_onSWFReady方法后,如果disable为true时就禁用,为false时就可上传:

  1. var disable = false; //全局变量
  2. //文件上传
  3. function uploadfile() {
  4. var config = {
  5. id: "file_upload",
  6. formKey: "formData",
  7. formData: { 'guid': $("#GUID").val(), 'attType': 'XM-PS-101', 'url': '/ProjectInfo/ProjectInfoAdd', 'urlID': $("#ID").val(), 'backUrl': $("#backUrl").val() },
  8. fileTypeDesc: '文件',
  9. fileTypeExts: '*.jpg;*.png;*.doc;*.docx;*.xls;*.xlsx;*.pdf',
  10. sfdisable: disable
  11. };
  12. upload(config);
  13. }

页面调用上传的方法

  1. <input type="button" name="file_upload" id="upload" style="width: 84px; height: 29px;" class="uploadify-button uploadify uploadify-button-text" value="选择文件" />
  2.  
  3. <input type="file" name="file_upload" id="file_upload" style="display:none"/>
  4. <ul id="filename" class="ulfile" style="padding-left: 20px"></ul>

页面的html

7.最终效果图:
      

作者:静水思寒
出处:http://www.cnblogs.com/jingshuisihan/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

在MVC中利用uploadify插件实现上传文件的功能的更多相关文章

  1. 利用ajaxfileupload插件异步上传文件

    html代码: <input type="file" id="imgFile" name="imgFile" /> js代码: ...

  2. 利用TortoiseGit向Github上传文件

    利用TortoiseGit向Github上传文件 第一步:建一个新文件夹,作为本地仓库 第二步:右键选择设置为版本库 若弹出,确认即可 重新打开改文件,会发现多了一个绿色的小勾 在文件夹中会自动生成一 ...

  3. ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案

    摘要: ueditor1.3.6jsp版在struts2应用中上传图片报"未找到上传文件"解决方案 在struts2应用中使用ueditor富文本编辑器上传图片或者附件时,即使配置 ...

  4. python中使用multipart/form-data请求上传文件

    最近测试的接口是上传文件的接口,上传单个文件,我主要使用了2种方法~ 接口例如: URL: http://www.baidu.com/*** method:post 参数: { "salar ...

  5. 编写Java程序,实现客户端向服务端上传文件的功能

    查看本章节 查看作业目录 需求说明: 实现客户端向服务端上传文件的功能 当启动服务端后,运行客户端程序,系统提示客户在客户端输入上传文件的完整路径.当客户在客户端输入完成后,服务端实现文件上传 实现思 ...

  6. c# asp.net mvc4 使用uploadify插件实现上传功能

    [1]首先去官网下载插件:http://www.uploadify.com/download/ .ww我使用的是免费的,基于flash的版本.因为基于H5的版本需付费使用,然后使用该插件也就是做做毕设 ...

  7. CI(2.2) 配置 jquery的上传插件Uploadify(v3.2) 上传文件

    1.下载uploadify,   我的是v3.2 2.模板页面引入: <base href='{base_url()}' /> <script type="text/jav ...

  8. shell中利用ftp 上传文件夹功能

    我们知道ftp 只能用来上传或者下载文件,一次单个或者多个,怎么实现将文件夹的上传和下载呢? 可以利用先在remote ip上建立一个相同的文件夹目录,然后将文件放到各自的目录中去 1.循环遍历出要上 ...

  9. .net MVC借助Iframe实现无刷新上传文件

    html: <div id="uploadwindow" style="display: none;"> <form action=" ...

随机推荐

  1. web前端开发框架搜集

    Web应用框架(Web application framework)是一种电脑软件框架,用来支持动态网站.网络应用程序及网络服务的开发.这种框架有助于减轻网页开发时共通性活动的工作负荷,例如许多框架提 ...

  2. Cocos2d粒子系统二

    粒子系统的属性: 粒子的发射速度 重力模式(模式A): 重力 方向 速度 +- 变动 切向加速度 +- 变动 径向加速度 +- 变动 半径模式(模式B): 开始半径 +- 变动 结束半径 +- 变动 ...

  3. C语言初学 给已知公式求圆周率

    公式: 圆周率=1-1/3+1/5-1/7+......+1/(4n-3)-1/(4n-1) #include<stdio.h> #include<math.h> main() ...

  4. javaWeb防止恶意登陆或防盗链的使用

    使用场景:明明引用了一个正确的图片地址,但显示出来的却是一个红叉或写有“此图片仅限于***网站用户交流沟通使用”之类的“假图片”.用嗅探软件找到了多媒体资源的真实地址用下载软件仍然不能下载.下载一些资 ...

  5. 02 - 替换SetInput方法 VTK 6.0 迁移 (2013-06-30 16:22)

    VTK6 引入了许多不兼容的变化,这其中就包括用SetInputData()和SetInputConnection()替换SetInput()方法.在先前的版本中,VTK4 引入了SetInput() ...

  6. startActivityForResult案例

    Info:startActivty 与 startActivityForResult区别 (1):startActivity 启动了其他Activity之后不会再回调过来,此时启动者与被启动者在启动后 ...

  7. TimeZone 时区 (JS .NET JSON MYSQL)

    来源参考 : http://www.cnblogs.com/qiuyi21/archive/2008/03/04/1089456.html 来源参考 : http://walkingice.blogs ...

  8. WPF自定义控件与样式(15)-终结篇

    原文:WPF自定义控件与样式(15)-终结篇 系列文章目录  WPF自定义控件与样式(1)-矢量字体图标(iconfont) WPF自定义控件与样式(2)-自定义按钮FButton WPF自定义控件与 ...

  9. Qt入门(3)——信号和槽

    信号和槽用于对象间的通讯.信号/槽机制是Qt的一个中心特征并且也许是Qt与其它工具包的最不相同的部分.在图形用户界面编程中,我们经常希望一个窗口部件的一个变化被通知给另一个窗口部件.更一般地,我们希望 ...

  10. 2015第24周四Spring事务4

    Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource.TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分.     Da ...