1.在视图中显示上传按钮
<div class="control-group"> <label class="control-label">资料附件:</label> <div class="controls"> <input type="file" id="DataAppend" style="display:none" value="上传" /> <input type="text" style="width:600px" readonly="true" id="showtxt" name="DataAppend" value="@Model.DataAppend" /> <input type="button" id="sc" name="name" value="上传" /> </div> </div>
一个type='file' 的input 一个type='button'的input
在js中写点击上传事件
$("#sc").click(function () { $("#DataAppend").click(); }) $('#DataAppend').fileupload({ dataType: 'json', url: "/HOS/Apprentice/SmritiDataUpload", progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .bar').css({ 'width': progress + '%', 'height': '5px' } ); }, done: function (e, data) { debugger; if (data.result[0].result != "OK") { $('#progress .bar').css({ 'width': '0%', 'height': '0px' }); alert(data.result[0].result); } else { debugger; $("#showtxt").val(data.result[0].url); } } });
点击上传按钮时实现上传事件 .fileupload()
走入后台控制器SmritiDataUpload方法
[HttpPost] public ActionResult SmritiDataUpload() { var result = new List<ViewDataUploadFilesResult>(); try { foreach (string file in Request.Files) { var statuses = new List<ViewDataUploadFilesResult>(); var headers = Request.Headers; if (string.IsNullOrEmpty(headers["X-File-Name"])) { UploadWholeFile(Request, statuses, "file"); } else { UploadPartialFile(headers["X-File-Name"], Request, statuses); } JsonResult jsonresult = Json(statuses); jsonresult.ContentType = "text/plain"; return jsonresult; } return Json(result); } catch (Exception) { throw; } }
上面的方法中包含两个方法,一个是UploadWholeFile()和UploadPartialFile()方法
当不存在headers["X-File-Name"]时走入UploadWholeFile()方法===上传多个文件,存在走入UploadPartialFile()方法
在UploadWholeFile()文件中 需要先判断上传文件的文件类型是否是有效文件
private string ISValid(HttpPostedFileBase file, string dirName) { //定义允许上传的文件扩展名 Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp"); extTable.Add("flash", "swf,flv"); extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,pdf"); //extTable.Add("file", "doc,docx,pdf"); //最大文件大小 int maxSize = 2000000; String fileName = file.FileName; String fileExt = Path.GetExtension(fileName).ToLower(); if (file.InputStream == null || file.InputStream.Length > maxSize) { return "上传文件大小超过限制。"; } if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) { return "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。"; } return "OK"; }
将有效的文件类型
上传各种文件类型之前首先要对上传的文件进行验证,检验是否是有效文件。如果需要添加新的文件类型,可以在哈希表中添加新的键值。
下面贴出UploadWholeFile()和UploadPartialFile()方法
private void UploadWholeFile(HttpRequestBase request, List<ViewDataUploadFilesResult> statuses, string type = "image") { for (int i = 0; i < request.Files.Count; i++) { string result = ISValid(request.Files[i], type); if (result != "OK") { statuses.Add(new ViewDataUploadFilesResult() { result = result }); } } if (statuses.Count > 0) return; for (int i = 0; i < request.Files.Count; i++) { var file = request.Files[i]; if (!Directory.Exists(StorageRoot)) { Directory.CreateDirectory(StorageRoot); } string fileExt = Path.GetExtension(file.FileName).ToLower(); Log4NetHelper.Error(LoggerType.WebExceptionLog, "原文件名:" + file.FileName, null); string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; Log4NetHelper.Error(LoggerType.WebExceptionLog, "新文件名:" + newFileName, null); var fullPath = Path.Combine(StorageRoot, newFileName); file.SaveAs(fullPath); ViewDataUploadFilesResult fileResult = new ViewDataUploadFilesResult() { result = "OK", name = newFileName, size = file.ContentLength, type = file.ContentType, url = Path.Combine(path, Path.GetFileName(newFileName)), delete_type = "GET", oldname = file.FileName, }; if (type == "image") { fileResult.thumbnail_url = @"data:image/png;base64," + EncodeFile(fullPath); } statuses.Add(fileResult); } }
private void UploadPartialFile(string fileName, HttpRequestBase request, List<ViewDataUploadFilesResult> statuses) { if (request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request"); var file = request.Files[0]; string result = ISValid(file, "image"); if (result != "OK") { statuses.Add(new ViewDataUploadFilesResult() { result = result }); } if (statuses.Count > 0) return; var inputStream = file.InputStream; if (!Directory.Exists(StorageRoot)) { Directory.CreateDirectory(StorageRoot); } string fileExt = Path.GetExtension(file.FileName).ToLower(); string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; var fullName = Path.Combine(StorageRoot, newFileName); using (var fs = new FileStream(fullName, FileMode.Append, FileAccess.Write)) { var buffer = new byte[1024]; var l = inputStream.Read(buffer, 0, 1024); while (l > 0) { fs.Write(buffer, 0, l); l = inputStream.Read(buffer, 0, 1024); } fs.Flush(); fs.Close(); } ViewDataUploadFilesResult fileResult = new ViewDataUploadFilesResult() { result = "OK", name = newFileName, size = file.ContentLength, type = file.ContentType, url = Path.Combine(path, Path.GetFileName(newFileName)), delete_type = "GET", }; if (fileExt.Contains("gif,jpg,jpeg,png,bmp")) { fileResult.thumbnail_url = @"data:image/png;base64," + EncodeFile(fullName); } statuses.Add(fileResult); }