最近在做一个图片上传到服务器的功能,之前基本没有什么JS的经验,用的也是网上的插件。做了一个星期才把他弄好,现在做一下总结,方便以后查看。
用的插件是WebUploader,上面有很多例子,我找的例子如下图:
在实例化WebUploader的时候需要修改upload.js文件中的server的地址,这样才能将指定的图片上传到服务器代码如下:
// 实例化 uploader = WebUploader.create({ pick: { id: '#filePicker', label: '点击选择图片' }, formData: { uid: 123 }, dnd: '#dndArea', paste: '#uploader', swf: 'Uploader.swf', chunked: false, chunkSize: 512 * 1024, server:'Handler1.ashx',//用来处理上传图片的服务 // runtimeOrder: 'flash', //文件过滤 accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' }, });
需要注意的是,Handler1.ashx是一个处理上传图片的服务,用于将上传的图片保存到服务器上,文件代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Net; using System.Web; using System.Web.Services; namespace JQueryUploadDemo { /// <summary> /// $codebehindclassname$ 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class UploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; HttpPostedFile file = context.Request.Files["Filedata"]; string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\"; if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } file.SaveAs(uploadPath + file.FileName); //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失 context.Response.Write("1"); } else { context.Response.Write("0"); } } public bool IsReusable { get { return false; } } } }
完成上传时候,前端需要获取服务器返回的数据,用于保存在数据库,找了半天,最后在webuploader.js的_finishFile函数中找到了,这里只显示部分代码:
// 完成上传。 _finishFile: function( file, ret, hds ) { var owner = this.owner; postfilename=ret._raw;//获取服务器返回的参数 return owner .request( 'after-send-file', arguments, function() { file.setStatus( Status.COMPLETE ); owner.trigger( 'uploadSuccess', file, ret, hds ); }) .fail(function( reason ) { // 如果外部已经标记为invalid什么的,不再改状态。 if ( file.getStatus() === Status.PROGRESS ) { file.setStatus( Status.ERROR, reason ); } owner.trigger( 'uploadError', file, reason ); }) .always(function() { owner.trigger( 'uploadComplete', file ); }); },