和分页类似,文件上传是web开发标配的技能之一。下面介绍Uploadify的配置和使用。
一、配置
首先到Uploadify官网下载,然后在项目中添加相应引用。前台代码如下:
1.jquery.js
2.uploadify/jquery.uploadify.js
3.uploadify/uploadify.css
js代码:
<script type="text/javascript"> $(function () { $("#uploadify").uploadify({ height: 30, width: 120, swf: ‘/uploadify/uploadify.swf‘, uploader: ‘uploadHandler.ashx‘, //‘folder‘: ‘uploadedFile‘, //不起作用 ‘auto‘: false, ‘buttonText‘: ‘浏 览‘, ‘multi‘: false, //‘onInit‘: function () { console.log("1"); }, ‘onSelect‘: function (fileObj) { console.info( "文件名:" + fileObj.name + "\r\n" + "文件大小:" + fileObj.size + "\r\n" + "创建时间:" + fileObj.creationDate + "\r\n" + "最后修改时间:" + fileObj.modificationDate + "\r\n" + "文件类型:" + fileObj.type ); }, ‘onUploadComplete‘: function (file) { console.log(‘The file ‘ + file.name + ‘ was uploaded.‘); }, ‘onUploadSuccess‘: function (file, data, response) { //console.log(‘The file ‘ + file.name + ‘ was successfully uploaded with a response of ‘ + response + ‘:‘ + data); //file.name : 文件名.jpg //response : true //data : 服务器返回来的数据 console.log("return url is : " + data); $("#imgPriview").attr(‘src‘, data); } }); }); </script>
html代码:
<div id=""> <img width="100px;" height="100px;" id="imgPriview" src="http://images4.c-ctrip.com/target/headphoto/portrait_180_180.jpg" alt="" /> </div> <input type="file" name="uploadify" id="uploadify" /> <p> <a href="javascript:$(‘#uploadify‘).uploadify(‘upload‘,‘*‘);">上传</a>| <a href="javascript:$(‘#uploadify‘).uploadify(‘cancel‘)"> 取消上传</a> </p>
点击上传以后,会将数据提交到后台,交给uploadHandler.ashx处理。
二、后台
一般处理程序ahsx会处理前台提交过来的数据,把图片保存到磁盘,然后返回图片的url给客户端进行预览。
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; HttpPostedFile file = context.Request.Files["Filedata"]; string uploadPath = context.Request.MapPath("/uploadedFiles/"); string fileName = file.FileName; string imgUrl = "http://" + context.Request.Url.Authority + "/uploadedFiles/" + fileName; if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } file.SaveAs(uploadPath + fileName); context.Response.Write(imgUrl); } else { context.Response.Write("0"); } }
一个简单的demo示范如何配置和使用Uploadify,安全性方面没有考虑。