在Web开发中,有很多可以上传的组件模块,利用HTML的File控件的上传也是一种办法,不过这种方式,需要处理的细节比较多,而且只能支持单文件的操作。在目前Web开发中用的比较多的,可能uploadify(参考
http://www.uploadify.com/
)也算一个吧,不过这个版本一直在变化,他们的脚本调用也有很大的不同,甚至调用及参数都一直在变化,很早的时候,那个Flash的按钮文字还没法变化,本篇随笔主要根据项目实际,介绍一下3.1版本的uploadify的控件使用,这版本目前还是最新的,因此对我们做Web开发来说,有一定的参考性。

这个控件有很多参数控制,以及事件的处理响应,相对来说也比较好用。参数控制可以控制上传文件多选、文件类型、文件大小、文件数量、检查文件是否存在,以及一些按钮参数的控制,如文字、高度、宽度等,对提交文件成功与否、完成操作、取消、停止上传等等都有控制,他们的帮助文档也写得比较完善,不过就是各个版本的方法参数完全不同了,但控件是一个好控件。

控件的使用首先要加入必备的脚本类库,由于该控件是利用了Jquery的功能,因此还需要应用Jquery脚本文件,如下所示。

    <script src="http://www.cnblogs.com/JQuery/jquery-1.8.0.min.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/JQueryTools/uploadify/jquery.uploadify-3.1.min.js" type="text/javascript"></script>
    <link href="http://www.cnblogs.com/JQueryTools/uploadify/uploadify.css" rel="stylesheet" type="text/css" />

配置控件的一些参数,以及相应的处理事件,如下所示。

    <script language="javascript" type="text/javascript">$(function () {var guid = '<%=Request["guid"] %>';var type = '<%=Request["type"] %>';if (guid == null || guid == "") {
guid
=newGuid();
}
if (type != null) {
type
= type + '/';
}

$(
'#file_upload').uploadify({'swf': 'uploadify.swf', //FLash文件路径 'buttonText': '浏 览', //按钮文本 'uploader': 'uploadhandler.ashx?guid=' + guid, //处理ASHX页面 'formData' : { 'folder' : 'picture' }, //传参数 'queueID': 'fileQueue', //队列的ID 'queueSizeLimit': 10, //队列最多可上传文件数量,默认为999 'auto': false, //选择文件后是否自动上传,默认为true 'multi': true, //是否为多选,默认为true 'removeCompleted': true, //是否完成后移除序列,默认为true 'fileSizeLimit': '10MB', //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值 'fileTypeDesc': 'Image Files', //文件描述 'fileTypeExts': '*.gif; *.jpg; *.png; *.bmp', //上传的文件后缀过滤器 'onQueueComplete': function (event, data) { //所有队列完成后事件//ShowUpFiles(guid, type, show_div); alert("上传完毕!");
},
'onUploadError': function (event, queueId, fileObj, errorObj) {
alert(errorObj.type
+ "" +errorObj.info);
}
});
});

function newGuid() {
var guid = "";for (var i = 1; i <= 32; i++){var n = Math.floor(Math.random()*16.0).toString(16);
guid
+=n;if((i==8)||(i==12)||(i==16)||(i==20))
guid
+= "-";
}
returnguid;
}
</script>

再次提一下,这个控件不要参考网上其他的一些说明,否则可能参数及用法不正确,一定要找到对应版本的说明(本篇指的是3.1.1),最好参考该版本的在线文档。

上面的参数,我基本上都给了注释了,还有一些不是很重要的参数,这里没有列出来,需要可以参考在线文档吧。

值得提到的是,这个版本可以修改Flash里面的文字,非常棒,很讨厌以前的那个默认Browse的英文,虽然以前替代图片可以修改文字,但是还是不太好用。这个直接修改文字,非常好。

值得注意的是uploader参数,这个是我们ashx的后台处理程序,就是控件提交文件给那个页面进行保存处理,添加数据库记录等操作。

页面代码使用很简单,如下所示

<bodystyle="margin-left:10px; margin-top:10px">
    <formid="form1"runat="server"enctype="multipart/form-data">
    <divid="fileQueue"class="fileQueue"></div>

    <div>
    <inputtype="file"name="file_upload"id="file_upload" />
        <p>
            <inputtype="button"class="shortbutton"id="btnUpload"onclick="javascript:$('#file_upload').uploadify('upload','*')"value="上传" />
            &nbsp;&nbsp;&nbsp;&nbsp;
            <inputtype="button"class="shortbutton"id="btnCancelUpload"onclick="javascript:$('#file_upload').uploadify('cancel')"value="取消" />
        </p>
        <divid="div_show_files"></div>
    </div>
    </form>
</body>

关键是后台上传文件的保存操作了,asp.net一般采用ashx的处理页面来处理。

    /// <summary>
    ///文件上传后台处理页面/// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo
=WsiProfiles.BasicProfile1_1)]public classUploadHandler : IHttpHandler
{
public voidProcessRequest(HttpContext context)
{
context.Response.ContentType
= "text/plain";
context.Response.Charset
= "utf-8";try{string guid = context.Request.QueryString["guid"];string folder = context.Request["folder"];//LogTextHelper.Info(folder); HttpPostedFile file= context.Request.Files["Filedata"];if (file != null)
{
string oldFileName = file.FileName;//原文件名 int size = file.ContentLength;//附件大小 string extenstion = oldFileName.Substring(oldFileName.LastIndexOf(".") + 1);//后缀名 string newFileName = GetNewFileName(oldFileName);//生成新文件名//LogTextHelper.Info(newFileName); #region 上传到远程服务器 //FileServerManage fsw = new FileServerManage();//string uploadFilePath = "/" + newFileName;//if (!string.IsNullOrEmpty(folder))//{//uploadFilePath = string.Format("/{0}/{1}", folder, newFileName);//}//bool uploaded = fsw.UploadFile(file.InputStream, "/" + folder + "/" + newFileName); #endregion #region 本地服务器上传AppConfig config= newAppConfig();string uploadFiles = config.AppConfigGet("uploadFiles");if (string.IsNullOrEmpty(uploadFiles))
{
uploadFiles
= "uploadFiles";
}
if (!string.IsNullOrEmpty(folder))
{
uploadFiles
=Path.Combine(uploadFiles, folder);
}
string uploadPath = Path.Combine(HttpContext.Current.Server.MapPath("/"), uploadFiles);if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
string newFilePath =Path.Combine(uploadPath, newFileName);
LogTextHelper.Info(newFilePath);
file.SaveAs(newFilePath);
bool uploaded =File.Exists(newFilePath);#endregion if(uploaded)
{
#region 文件保存成功后,写入附件的数据库记录 //AttachmentInfo attachmentInfo = new AttachmentInfo();//attachmentInfo.EditorTime = DateTime.Now;//attachmentInfo.FileExtend = extenstion;//attachmentInfo.FileName = folader + "/" + newFileName;//attachmentInfo.OldFileName = oldFileName;//attachmentInfo.Size = size;//attachmentInfo.Guid = guid;//BLLFactory<Attachment>.Instance.Insert(attachmentInfo); #endregion}
}
else{
LogTextHelper.Error(
"上传文件失败");
}
}
catch(Exception ex)
{
LogTextHelper.Error(
"上传文件失败", ex);throw;
}
}
/// <summary> ///获取新的名称 比如:aa.jpg转化为aa(20090504).jpg/// </summary> /// <param name="fileName">文件名称[aa.jpg]</param> /// <returns>新的文件名称</returns> public static string GetNewFileName(stringfileName)
{
if (string.IsNullOrEmpty(fileName))return string.Empty;//文件后缀名 string extenstion = fileName.Substring(fileName.LastIndexOf(".") + 1);string name = fileName.Substring(0, fileName.LastIndexOf(".")) + "(" + DateTime.Now.ToFileTime() + ")";string newFileName = name + "." +extenstion;returnnewFileName;
}
public boolIsReusable
{
get{return false;
}
}
}

执行例子的上传操作,我们会提示上传成功的操作,对应的目录下,会有相应的文件写入了。

以上就是这个批量上传文件控件uploadify的使用说明,供大家学习参考。

标签: none

添加新评论