先理清上传步骤,uploadify插件在与用户交互时首先是向用户索要需要上传的文件队列,当用户
选择好所有要上传的文件,点击上传按钮,插件首先确保文件大小是否符合客户端文件大小限
制,验证通过后逐个向服务器发送HTTP请求,这里处理HTTP请求的代码写在了ashx中,
$(function () { $('#file_upload').uploadify({ 'auto': false, 'successTimeout': 99999, 'swf': '../../Source/Style/Plugins/Uplodify/uploadify.swf', 'queueID': 'uploadfileQueue', 'buttonText': '选择文件', 'uploader': '../../Server/Ajax/System/UploadFilesHandler.ashx', 'fileSizeLimit': '0', 'queueSizeLimit': 5, 'progressData': 'speed', 'formData': { 'Path': 'Hr\\Video\\' }, //Path文件夹 'overrideEvents': ['onDialogClose'], 'fileTypeExts': '*.flv' }) })
ajax服务端代码如下:
try { HttpPostedFile File;//文件对象 string Path;//目录 string FileName;//文件名称 context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; File = context.Request.Files["FileData"]; Path = context.Request.Params["Path"]; if (Path != "") Path = Path + "\\"; FileName = File.FileName; FileName = Guid.NewGuid().ToString().ToUpper() + '.' + FileName.Substring(FileName.LastIndexOf('.')+1,FileName.Length - FileName.LastIndexOf(".") - 1); Path = context.Server.MapPath(ComFunction.GetConfig("UpLoadPath") + Path); //检测文件夹 if (Directory.Exists(Path) == false) Directory.CreateDirectory(Path); string newFileName = FileName; FileName = Path + FileName; File.SaveAs(FileName); context.Response.Write(newFileName); } catch (Exception e) { //出错的话返回0 context.Response.Write(e.Message); } }
后台首先取得文件名和存放文件路径,判断路径是否存在,不存在则创建文件夹,然后执行存储文件,调试能够正常上传。
这里为了使文件名不重复用到了Guid类随机生成文件名,从而直接避免了用户上传同名文件时的判断,最初想要先判断该文件夹下是否存在同名文件,不存在则存储文件,存在则询问用户是否替换,但这种做法不利于记录文件版本的更新状况,至此,文件上传从前台到后台的所有操作已完成。