html代码:
<input type="file" id='upload' name="upload" multiple="multiple" onchange="uploadFile(this);" style="display:none;" /> <button id='uploadbtn' class="rscUploadBtn" type="button" onclick="document.getElementById('upload').click();" >选择上传文件</button><br />
js代码:
//file为input[type=file]元素,例如:onchange="uploadFile(this);" function uploadFile(file) { if (file && file.files && file.files.length > 0) { //创建一个FormData空对象,然后使用append方法添加key/value var fd = new FormData(); for (var i = 0; i < file.files.length; i++) fd.append('file['+i+']',file.files[i]); fd.append("action", "filelistup"); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var data = JSON.parse(xhr.responseText); if (data.returnValue == 0) { //批量上传成功 //处理成功后的逻辑 //TODO:....... } else alert(data.returnMsg); } } //侦查当前附件上传情况 可以设置进度条 xhr.upload.onprogress = function (evt) { //var loaded = evt.loaded;//已经上传大小情况 //var tot = evt.total;//附件总大小 //var per = Math.floor(100 * loaded / tot); //已经上传的百分比,如35 } xhr.open("post", GetHost() + 'xxx/index.ashx'); xhr.send(fd); } }
c#接收文件代码:
/// <summary> /// 上传文件 /// </summary> /// <param name="httpRequest"></param> /// <param name="directoryName">保存文件的目录</param> /// <param name="extList">需要接收文件的后缀名,用来过滤</param> /// <param name="fileNames">接收成功后,保存文件的文件名</param> /// <param name="errorMsg">错误消息</param> /// <returns></returns> public static bool UploadFile(HttpRequestBase httpRequest, string directoryName,List<string> extList,out List<string> fileNames, out string errorMsg) { bool rc = false; errorMsg = ""; string fileFullName = ""; fileNames = new List<string>(); try { directoryName = (directoryName ?? "").Trim(); if (directoryName != "") { //如果不存在该文件夹,则创建一个 if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName); //如果创建失败 if (!Directory.Exists(directoryName)) errorMsg = string.Format("创建文件夹{0}失败!", directoryName); //存在该文件夹 else { foreach (string upload in httpRequest.Files) { if (!httpRequest.Files[upload].HasFile()) continue; //获取 上传文件的名称 string filename = Path.GetFileName(httpRequest.Files[upload].FileName); //获取 上传文件的扩展名 string ext = Path.GetExtension(filename); //检查 文件扩展名 if (extList != null && extList.Count > 0) { if (!extList.Contains(ext)) { errorMsg = string.Format("不支持{0}格式文件的上传!", ext); return false; } } //使用guid当做当前文件的文件名 filename = Guid.NewGuid().ToString().Replace("-", "") + ext; //组合保存文件的全路径名 fileFullName = Path.Combine(directoryName, filename); httpRequest.Files[upload].SaveAs(fileFullName); if (File.Exists(fileFullName)) fileNames.Add(filename); else { foreach (var fname in fileNames) { string flname = Path.Combine(directoryName, fname); if (File.Exists(flname)) File.Delete(flname); } rc = false; break; } rc = true; } } } else { errorMsg = "上传文件失败!"; log.Error("存放文件的文件夹名称不能为空!"); } } catch (Exception ex) { log.Error("AddFile", ex); errorMsg = "上传文件失败!"; } log.DebugFormat("上传文件[{0}]{1} {2}", fileFullName, rc ? "成功!" : "失败!", errorMsg); return rc; }
c#代码调用示例:
//获取评论图片的保存目录 string directoryName = Utils.GetMapPath("/upload/img"); //需要过滤的图片文件后缀名 List<string> ext = new List<string> { }; //图片文件保存成功后获取的图片名称 List<string> fileNames = null; string errorMsg = ""; //保存图片文件 if (Common.UploadFile(HttpContext.Current.Request.RequestContext.HttpContext.Request, directoryName, ext, out fileNames, out errorMsg)) {
//返回文件的相对路径名字符串数组 rc.SetReturnData(fileNames.Select(it=> Common.GetRelativePath(Path.Combine(directoryName, it))).ToList()); rc.SetResult(ErrorCode.Success); } else rc.SetResult(ErrorCode.Failed); rc.SetContentType("text/html");