当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.net MVC中使用JQuery插件ajaxFileUpload上传文件

Asp.net MVC中使用JQuery插件ajaxFileUpload上传文件

2017年12月12日  | 移动技术网IT编程  | 我要评论

我的个神啊 下载,男色天下图片,猪的养殖技术

0 ajaxfileupload简介 

ajaxfileupload插件是一个非常简单的基于jquery的异步上传文件的插件,使用过程中发现很多与这个同名的,基于原始版本基础之上修改过的插件,文件版本比较多,我把我自己使用的ajaxfileupload文件上传到博客园上了,想要使用的朋友可以下载:。 

整个插件源码不到200行,实现非常简单,大致原理就是通过js动态创建隐藏的表单,然后进行提交操作,达到附件上传的目的,主要实现在源码里都有注释,不难理解,我们也可以基于此简单版本实现更复杂的操作。 

1 ajaxfileupload使用说明 

ajaxfileupload的使用也很简单,调用ajaxfileupload方法即可,各配置项详细说明如下: 

$.ajaxfileupload({
   type: "post",       //请求类型:post或get,当要使用data提交自定义参数时一定要设置为post
   url: "/shared/upload",     //文件上传的服务器端请求地址
   secureuri: false,      //是否启用安全提交,一般默认为false就行,不用特殊处理
   fileelementid: "filepicture",   //文件上传控件的id <input type="file" id="filepicture" name="filepicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filepicturechange()" />
   datatype: "json",      //返回值类型,一般设置为json,还支持html\xml\script类型
   data: { "id": "1", "name": "test" }, //用于post请求提交自定义参数
   success: function (data, status) {  //服务器成功响应处理函数
   },
   error: function (data, status, e) { //服务器响应失败处理函数
   }
  });

首先在页面添加对jquery及ajaxfileupload的引用,这里的jquery用的2.1.4版本,经测试用各个版本基本没什么影响。
 <script src="../../content/js/jquery-2.1.4.min.js"></script>
<script src="../../content/js/ajaxfileupload.js"></script>
页面添加类型为file的input标签
 

复制代码 代码如下:
<input type="file" id="filepicture" name="filepicture" accept=".jpg,.jpeg,.png,.bmp" onchange="filepicturechange()" />

通过accept可以限定打开文件选择对话框后,默认能选择的文件类型。文件类型的定义主要有以下这些 

*.3gpp  audio/3gpp, video/3gpp  3gpp audio/video

*.ac3   audio/ac3   ac3 audio

*.asf   allpication/vnd.ms-asf  advanced streaming format

*.au    audio/basic au audio

*.css   text/css    cascading style sheets

*.csv   text/csv    comma separated values

*.doc   application/msword  ms word document

*.dot   application/msword  ms word template

*.dtd   application/xml-dtd document type definition

*.dwg   image/vnd.dwg   autocad drawing database

*.dxf   image/vnd.dxf   autocad drawing interchange format

*.gif   image/gif   graphic interchange format

*.htm   text/html   hypertext markup language

*.html  text/html   hypertext markup language

*.jp2   image/jp2   jpeg-2000

*.jpe   image/jpeg  jpeg

*.jpeg  image/jpeg  jpeg

*.jpg   image/jpeg  jpeg

*.js    text/javascript, application/javascript javascript

*.json  application/json    javascript object notation

*.mp2   audio/mpeg, video/mpeg  mpeg audio/video stream, layer ii

*.mp3   audio/mpeg  mpeg audio stream, layer iii

*.mp4   audio/mp4, video/mp4    mpeg-4 audio/video

*.mpeg  video/mpeg  mpeg video stream, layer ii

*.mpg   video/mpeg  mpeg video stream, layer ii

*.mpp   application/vnd.ms-project  ms project project

*.ogg   application/ogg, audio/ogg  ogg vorbis

*.pdf   application/pdf portable document format

*.png   image/png   portable network graphics

*.pot   application/vnd.ms-powerpoint   ms powerpoint template

*.pps   application/vnd.ms-powerpoint   ms powerpoint slideshow

*.ppt   application/vnd.ms-powerpoint   ms powerpoint presentation

*.rtf   application/rtf, text/rtf   rich text format

*.svf   image/vnd.svf   simple vector format

*.tif   image/tiff  tagged image format file

*.tiff  image/tiff  tagged image format file

*.txt   text/plain  plain text

*.wdb   application/vnd.ms-works    ms works database

*.wps   application/vnd.ms-works    works text document

*.xhtml application/xhtml+xml   extensible hypertext markup language

*.xlc   application/vnd.ms-excel    ms excel chart

*.xlm   application/vnd.ms-excel    ms excel macro

*.xls   application/vnd.ms-excel    ms excel spreadsheet

*.xlt   application/vnd.ms-excel    ms excel template

*.xlw   application/vnd.ms-excel    ms excel workspace

*.xml   text/xml, application/xml   extensible markup language

*.zip   aplication/zip  compressed archive

我这里没有单独放上传按钮,添加了onchange事件,在选择文件后立即上传文件,onchange时间定义如下。 

function filepicturechange() {
   $.ajaxfileupload({
    url: "/shared/upload", //用于文件上传的服务器端请求地址
     type: "post",
    secureuri: false, //一般设置为false
    fileelementid: "filepicture", //文件上传空间的id属性
     datatype: "json", //返回值类型 一般设置为json
    success: function (data, status) { //服务器成功响应处理函数
      alert(data.filename);
     alert(data.filepath);
     alert(data.filesize);
    },
    error: function (data, status, e){ //服务器响应失败处理函数
      alert(e);
    }
   });
  };

后台控制器处理方法如下,使用md5处理,判断文件是否已经存在,避免文件重复上传。 

/// <summary>
  /// 附件上传
  /// </summary>
  /// <returns></returns>
  public actionresult upload()
  {
   httpfilecollection files = system.web.httpcontext.current.request.files;
   if (files.count == 0) return json("faild", jsonrequestbehavior.allowget);
   md5 md5hasher = new md5cryptoserviceprovider();
   /*计算指定stream对象的哈希值*/
   byte[] arrbythashvalue = md5hasher.computehash(files[0].inputstream);
   /*由以连字符分隔的十六进制对构成的string,其中每一对表示value中对应的元素;例如“f-2c-4a”*/
   string strhashdata = system.bitconverter.tostring(arrbythashvalue).replace("-", "");
   string fileeextension = path.getextension(files[0].filename);
   string uploaddate = datetime.now.tostring("yyyymmdd");
   string virtualpath = string.format("/data/componentattachments/{0}/{1}{2}", uploaddate, strhashdata, fileeextension);
   string fullfilename = server.mappath(virtualpath);
   //创建文件夹,保存文件
    string path = path.getdirectoryname(fullfilename);
   directory.createdirectory(path);
   if (!system.io.file.exists(fullfilename))
   {
    files[0].saveas(fullfilename);
   }
   string filename = files[0].filename.substring(files[0].filename.lastindexof("\\") + 1, files[0].filename.length - files[0].filename.lastindexof("\\") - 1);
   string filesize = getfilesize(files[0].contentlength);
   return json(new { filename = filename, filepath = virtualpath, filesize = filesize }, "text/html", jsonrequestbehavior.allowget);
  }
  /// <summary>
  /// 获取文件大小
  /// </summary>
  /// <param name="bytes"></param>
  /// <returns></returns>
  private string getfilesize(long bytes)
  {
   long kblength = 1024;
   long mblength = 1024 * 1024;
   if (bytes < kblength)
    return bytes.tostring() + "b";
   if (bytes < mblength)
    return decimal.round(decimal.divide(bytes, kblength), 2).tostring() + "kb";
   else
    return decimal.round(decimal.divide(bytes, mblength), 2).tostring() + "mb";
  }

2 ajaxfileupload使用过程中的一些问题
2.0 jquery.handleerror is not a function 

解决方法:
 经测试handlererror只在jquery-1.4.2之前的版本中存在,以后版本中都没有这个函数了,因此在将handleerror这个函数复制到ajaxfileupload.js中,就行了 

 uploadhttpdata: function (r, type) {
  var data = !type;
  data = type == "xml" || data ? r.responsexml : r.responsetext;
  // if the type is "script", eval it in global context
  if (type == "script")
   jquery.globaleval(data);
  // get the javascript object, if json is used.
  if (type == "json")
   eval("data = " + data);
   //eval("data = \"" + data + "\"");
  // evaluate scripts within html
  if (type == "html")
   jquery("<div>").html(data).evalscripts();

  return data;
 },
 handleerror: function (s, xhr, status, e) {
  // if a local callback was specified, fire it
  if (s.error) {
   s.error.call(s.context || s, xhr, status, e);
  }

  // fire the global callback
  if (s.global) {
   (s.context ? jquery(s.context) : jquery.event).trigger("ajaxerror", [xhr, s, e]);
  }
 }

更多精彩内容,请点击《jquery上传操作汇总》,进行深入学习和研究。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网