和分页类似,文件上传是web开发标配的技能之一。下面介绍Uploadify的配置和使用。
一、配置
首先到Uploadify官网下载,然后在项目中添加相应引用。前台代码如下:
1.jquery.js
2.uploadify/jquery.uploadify.js
3.uploadify/uploadify.css
js代码:
$("#uploadify1").uploadify({
height: 30,
120,
swf: '@Url.Content("~/Content/uploadify/uploadify.swf")',
uploader: '@Url.Content("~/Home/Upload")',
'auto': true,
'buttonText': '上传图片',
'multi': false,
'sizeLimit' : 2*1024*1024,
'formData': { 'submitType': 'image', 'studentId':studentId, 'taskId':taskId },
'fileTypeDesc': '指定文件',
'fileTypeExts': '*.jpg; *.jpeg; *.png; *.gif',
'removeTimeout': 2, //进度条消失秒数
'onInit': function () { },
'onSelect': function (fileObj) { //判断文件大小
var fileSize = fileObj.size;
if (fileSize > 2*1024*1024) {
alert("图片不得大于2M");
$('#uploadify1').uploadify('cancel');
return;
}
},
'onUploadComplete': function (file) {
},
'onUploadSuccess': function (file, data, response) { //上传成功回调方法
data = JSON.parse(data);
if(data.IsSuccess == "True" ){
alert("上传成功");
}else{
alert("上传失败");
return;
}
}
});
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,由于Uploadify是基于Flash上传的,有一个已知的bug是上传时会丢失sessionId,进而服务端也拿不到cookie, 好在可以通过手动添加sessionId解决。

