
遇到上传文件的问题,结合之前用到过的swfUpload,又找了一个无刷新上传文件的jquery插件uploadify,写篇博客记录一下分别介绍这两个的实现方法
swfUpload 导入swfUpload的开发包 添加js引用,引用swfUpload.js与handler.js文件,如果对swfUpload不了解、有疑问可以看看这篇文章 页面初始化


修改handler.js文件中 上传成功的事件,serverData是服务器端的响应

Uploadify 导入uploadify开发包,从官网下载,官网文档,中文文档,官网示例 添加js与css的引用,jquery.uploadify.js 、uploadify.css
(注:在css中引用uploadify-cancel.png图片文件的路径是可能不正确,可以在uploadify.css文件中自己进行更改)
页面初始化
页面初始化时,可以指定许多设置,并对上传成功的事件进行重载,data表示服务器端的响应

服务器端上传处理程序

//uploadify初始化
$(function () {
$('#file_upload').uploadify({
//指定swf
'swf': '/uploadify/uploadify.swf',
//服务器端处理程序
'uploader': '/Admin/UploadFileHandler.ashx',
//按钮文本
buttonText: '上传附件',
//文件类型
fileTypeExts: "*.zip;*.rar;*.doc;*.docx;*.xls;*xlsx",
onUploadSuccess: OnFileUploadSuccess
});
});
function OnFileUploadSuccess(file, data, response) {
//服务器端响应
if (data == 'noPermission') {
alert('没有上传权限');
}
if (data == 'Error') {
alert('上传失败');
} else if (response) {
alert('上传成功~~~');
$("#filePath").val(data);
}
}
uploadify
/// <summary>
/// 上传文件
/// </summary>
public class UploadFileHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//验证上传权限
if (context.Session["User"] == null)
{
context.Response.Write("no permission");
context.Response.End();
return;
}
try
{
//获取上传文件
//Filedata是客户端已经定义好的,如果想要更改,更改js文件中的配置
HttpPostedFile image_upload = context.Request.Files["Filedata"];
//获取文件扩展名
string fileExt = System.IO.Path.GetExtension(image_upload.FileName).ToLower();
//验证文件扩展名是否符合要求,是否是允许的图片格式
if (!FileTypes.IsAllowed(fileExt))
{
return;
}
//当前时间字符串
string timeString = DateTime.Now.ToString("yyyyMMddHHmmssfff");
//保存虚拟路径构建
string path = "/Upload/" + timeString + fileExt;
//获取、构建要上传文件的物理路径
string serverPath = context.Server.MapPath("~/" + path);
//保存图片到服务器
image_upload.SaveAs(serverPath);
//以上所述就是本文的全部内容了,希望大家能够喜欢。
