/// <summary> /// 检测是否符合上传文件格式 /// </summary> /// <param name="uploadConfig">配置信息</param> /// <param name="filename">文件名字</param> /// <returns></returns> private bool CheckFileType(UeditorUploadConfig uploadConfig, string filename) { var fileExtension = Path.GetExtension(filename).ToLower(); var res = false; foreach (var item in uploadConfig.AllowExtensions) { if (item == fileExtension) { res = true; break; } } return(res); }
/// <summary> /// 检测是否符合上传文件大小 /// </summary> /// <param name="uploadConfig">配置信息</param> /// <param name="size">文件大小</param> /// <returns></returns> private bool CheckFileSize(UeditorUploadConfig uploadConfig, int size) { return(size < uploadConfig.SizeLimit); }
/// <summary> /// 百度编辑器的文件上传 /// </summary> /// <param name="uploadConfig">上传配置信息</param> /// <returns></returns> public ActionResult UEditorUpload(UeditorUploadConfig uploadConfig) { UeditorUploadResult result = new UeditorUploadResult() { State = UeditorUploadState.Unknown }; byte[] uploadFileBytes = null; string uploadFileName = null; if (uploadConfig.Base64) { uploadFileName = uploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[uploadConfig.UploadFieldName]); } else { var file = Request.Files[uploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadConfig, uploadFileName)) { return(Content(new { state = GetStateMessage(UeditorUploadState.TypeNotAllow) }.ToJson())); } if (!CheckFileSize(uploadConfig, file.ContentLength)) { return(Content(new { state = GetStateMessage(UeditorUploadState.SizeLimitExceed) }.ToJson())); } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { return(Content(new { state = GetStateMessage(UeditorUploadState.NetworkError) }.ToJson())); } } result.OriginFileName = uploadFileName; var savePath = UeditorPathFormatter.Format(uploadFileName, uploadConfig.PathFormat); var localPath = Server.MapPath(savePath).Replace("\\Utility\\", "\\ueditor\\");// +"/ueditor/net"; try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } System.IO.File.WriteAllBytes(localPath, uploadFileBytes); result.Url = savePath; result.State = UeditorUploadState.Success; } catch (Exception e) { result.State = UeditorUploadState.FileAccessError; result.ErrorMessage = e.Message; } return(Content(new { state = GetStateMessage(result.State), url = result.Url, title = result.OriginFileName, original = result.OriginFileName, error = result.ErrorMessage }.ToJson())); }