public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); try { #region 再需要储存文件到服务器 //if (!Directory.Exists(Path.GetDirectoryName(localPath))) //{ // Directory.CreateDirectory(Path.GetDirectoryName(localPath)); //} //File.WriteAllBytes(localPath, uploadFileBytes); //Result.Url = savePath; //Result.State = UploadState.Success; #endregion #region 文件到七牛 var ret = QiniuHelper.GetResult(uploadFileBytes); if (ret.OK) { Result.Url = QiniuHelper.GetUrl(ret.key); Result.State = UploadState.Success; } #endregion } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]); } else { var file = Request.Form.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize((int)file.Length)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.Length]; try { file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Path.Combine(Config.WebRootPath, savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public Crawler Fetch() { if (!IsExternalIPAddress(this.SourceUrl)) { State = "INVALID_URL"; return(this); } var request = HttpWebRequest.Create(this.SourceUrl) as HttpWebRequest; using (var response = request.GetResponseAsync().Result as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { State = "Url returns " + response.StatusCode + ", " + response.StatusDescription; return(this); } if (response.ContentType.IndexOf("image") == -1) { State = "Url is not an image"; return(this); } ServerUrl = PathFormatter.Format(Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat")); //var savePath = Path.Combine(Config.WebRootPath, ServerUrl); var savePath = Path.Combine(Config.GetString("catcherSaveAbsolutePath"), ServerUrl); // try { var stream = response.GetResponseStream(); // if (Config.GetValue <bool>("catcherFtpUpload")) { var fileExt = ServerUrl.Substring(savePath.LastIndexOf('.')).TrimStart('.'); var key = Config.GetString("catcherPathFormat") + "." + fileExt; //FtpUpload.UploadFile(stream, savePath, Consts.ImgFtpServer.ip, // Consts.ImgFtpServer.account, Consts.ImgFtpServer.pwd); AliyunOssUpload.UploadFile(Consts.AliyunOssServer.AccessEndpoint, Consts.AliyunOssServer.AccessKeyId, Consts.AliyunOssServer.AccessKeySecret, Consts.AliyunOssServer.BucketName, key, fileExt, stream); } else { if (!Directory.Exists(Path.GetDirectoryName(savePath))) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } var reader = new BinaryReader(stream); byte[] bytes; using (var ms = new MemoryStream()) { byte[] buffer = new byte[4096]; int count; while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, count); } bytes = ms.ToArray(); } File.WriteAllBytes(savePath, bytes); } State = "SUCCESS"; } catch (Exception e) { State = "抓取错误:" + e.Message; } return(this); } }
internal static string?FormatOldName(string oldName) => PathFormatter.FormatOldName(oldName);
public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); string vdir = function.PToV(Path.GetDirectoryName(localPath)) + "/"; string fname = Path.GetFileName(localPath); if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } try { if (UploadConfig.IsBar)//压缩图片,水印,如访问量大,应将其生成临时表 { var file = Request.Files[UploadConfig.UploadFieldName]; M_GuestBookCate model = GetBarModel(UploadConfig); if (model == null) { throw new Exception("贴吧图片上传出错,model的值为空"); } if (model.ZipImgSize > 0 && file.ContentLength > (model.ZipImgSize * 1024)) { imghelper.CompressImg(file, model.ZipImgSize, savePath);//需改为读取版面配置 } else { ZLLog.L("here2"); //string fname = Path.GetFileName(localPath); savePath = SafeSC.SaveFile(vdir, fname, uploadFileBytes); //File.WriteAllBytes(localPath, uploadFileBytes); } savePath = ImgHelper.AddWater(savePath); } else { savePath = SafeSC.SaveFile(vdir, fname, uploadFileBytes); savePath = ImgHelper.AddWater(savePath); } Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; Stream fileStream = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]); } else { var file = Request.Form.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize((int)file.Length)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.Length]; try { fileStream = file.OpenReadStream(); file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); //var localPath = Path.Combine(Config.WebRootPath, savePath); var localPath = Path.Combine(UploadConfig.SaveAbsolutePath, savePath); try { if (UploadConfig.FtpUpload) { var fileExt = Path.GetExtension(uploadFileName).TrimStart('.'); var key = savePath;//UploadConfig.PathFormat + "." + fileExt; //FtpUpload.UploadFile(new MemoryStream(uploadFileBytes), localPath, UploadConfig.FtpIp, // UploadConfig.FtpAccount, UploadConfig.FtpPwd); AliyunOssUpload.UploadFile(Consts.AliyunOssServer.AccessEndpoint, Consts.AliyunOssServer.AccessKeyId, Consts.AliyunOssServer.AccessKeySecret, Consts.AliyunOssServer.BucketName, key, fileExt, new MemoryStream(uploadFileBytes)); } else { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); } Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
private string CoverCoverCachedPath() { return(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", PathFormatter.GetCacheDirectory(), Metadata.Id.ToString(CultureInfo.InvariantCulture), Metadata.Images.Cover.GetFileExtension())); }
public Crawler Fetch() { if (!IsExternalIpAddress(this.SourceUrl)) { State = "INVALID_URL"; return(this); } var request = WebRequest.Create(this.SourceUrl) as HttpWebRequest; using (var response = request.GetResponse() as HttpWebResponse) { if (response != null && response.StatusCode != HttpStatusCode.OK) { State = "Url returns " + response.StatusCode + ", " + response.StatusDescription; return(this); } if (response != null && response.ContentType.IndexOf("image", StringComparison.Ordinal) == -1) { State = "Url is not an image"; return(this); } var sourceUri = new Uri(this.SourceUrl); ServerUrl = PathFormatter.Format(Path.GetFileName(sourceUri.AbsolutePath), Config.GetString("catcherPathFormat")); var savePath = Path.Combine(Config.WebRootPath, ServerUrl); //判断是否启用Oss存储 if (Config.GetBool("UseOss")) {//启用OSS存储 try { string extension = Path.GetExtension(Path.GetFileName(sourceUri.AbsolutePath)); var key = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(10000, 99999) + extension; ServerUrl = Config.GetString("OssViewBaseUrl") + key; OssApiHelper ossApiHelper = new OssApiHelper(); if (response != null) { var stream = response.GetResponseStream(); var result = ossApiHelper.PutObject(key, stream); if (result.Code == 0) { State = "SUCCESS"; } else { State = "Upload Oss Error:" + result.Message; } } else { State = "SUCCESS"; } } catch (Exception e) { State = "抓取错误:" + e.Message; } } else {//本地存储 if (!Directory.Exists(Path.GetDirectoryName(savePath))) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } try { if (response != null) { var stream = response.GetResponseStream(); var reader = new BinaryReader(stream); byte[] bytes; using (var ms = new MemoryStream()) { byte[] buffer = new byte[4096]; int count; while ((count = reader.Read(buffer, 0, buffer.Length)) != 0) { ms.Write(buffer, 0, count); } bytes = ms.ToArray(); } File.WriteAllBytes(savePath, bytes); } State = "SUCCESS"; } catch (Exception e) { State = "抓取错误:" + e.Message; } } return(this); } }
public void Test_FormatTextForFileNameOnly(string name, string oldName, string expectedText, string expectedSuffix) { PathFormatter.FormatTextForFileNameOnly(name, oldName).Should().Be((expectedText, expectedSuffix)); }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { var file = Request.Files[0];//Request.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; string fileExt = Path.GetExtension(uploadFileName).ToLower(); string saveDoc = DateTime.Now.ToString(@"yy\\MM\\dd\\"); string rndFileName = FancyFix.Tools.Usual.Common.GetDataShortRandom(); string dirPath = UploadConfig.PathFormat;// uploadFileName;//PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); string newFileName = saveDoc + rndFileName + fileExt; string newSmallFileName = saveDoc + rndFileName + "s" + fileExt; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); try { if (!Directory.Exists(dirPath + saveDoc)) { Directory.CreateDirectory(dirPath + saveDoc); } File.WriteAllBytes(dirPath + newFileName, uploadFileBytes); ImageTools.SetImgSize(dirPath + newFileName, 800, 800); if (UploadConfig.PathFormat.IndexOf("product") > 0) { Setting setting = UploadProvice.Instance().Settings["product"]; if (setting.AddWaterMark) { ImageTools.AddWaterMark(dirPath + newFileName, dirPath + newFileName, Server.MapPath(setting.WaterMarkImgOrTxt), WaterMarkType.ImageMark, WaterMarkPosition.Right_Bottom, setting.Transparency); } } //Tools.Tool.ImageTools.CreateSmallImage(dirPath + newFileName, dirPath + newSmallFileName, 200, 200); Result.Url = FancyFix.Tools.Usual.Utils.GetLastFolderName(dirPath) + "/" + newFileName; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; FancyFix.Tools.Tool.LogHelper.WriteLog(typeof(UploadHandler), e); } finally { WriteResult(); } }
private static Task <int> ExecuteAsync(CancellationToken cancellationToken) { var includePattern = _includesOption.Values; var excludePattern = _excludesOption.Values; // When no include pattern is specified, we decide to include all recursive ('**') if (!includePattern.Any()) { includePattern.Add("**"); } var matcher = new Matcher(StringComparison.OrdinalIgnoreCase); matcher.AddIncludePatterns(includePattern); matcher.AddExcludePatterns(excludePattern); var stopwatch = Stopwatch.StartNew(); var items = matcher.Execute(_pathArgument.Value); int totalItems = items.Count; TimeSpan getItemsElapsed = stopwatch.Elapsed; void ExecuteWithProgressBar(Action <string> itemAction, Action <DirectoryInfo, Func <bool> > rootPathAction) { var options = new ProgressBarOptions { ProgressCharacter = '─', CollapseWhenFinished = false }; using var progressBar = new ProgressBar(totalItems, "Start remove items...", options); var i = 0; foreach (string path in items.OrderByDescending(x => x.Length)) { string shrinkedPath = PathFormatter.ShrinkPath(path, Console.BufferWidth - 44); progressBar.Message = $"Remove item {i + 1} of {totalItems}: {shrinkedPath}"; itemAction(path); progressBar.Tick($"Removed item {i + 1} of {totalItems}: {shrinkedPath}"); ++i; } var rootPathDirectoryInfo = new DirectoryInfo(matcher.RootPath); var rootPathCheck = new Func <bool>(() => rootPathDirectoryInfo.Exists && rootPathDirectoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories).Length == 0); if ((_skipPathOption.HasValue() || !rootPathCheck()) && (_skipPathOption.HasValue() || !_tryRunOption.HasValue())) { return; } using ChildProgressBar childProgressBar = progressBar.Spawn(1, "child actions", options); { string shrinkedPath = PathFormatter.ShrinkPath(matcher.RootPath, Console.BufferWidth - 44); childProgressBar.Message = $"Remove empty root path: {shrinkedPath}"; rootPathAction(rootPathDirectoryInfo, rootPathCheck); childProgressBar.Tick($"Removed empty root path: {shrinkedPath}"); } } void ExecuteQuiet(Action <string> itemAction, Action <DirectoryInfo, Func <bool> > rootPathAction) { foreach (string path in items.OrderByDescending(x => x.Length)) { itemAction(path); } var rootPathDirectoryInfo = new DirectoryInfo(matcher.RootPath); var rootPathCheck = new Func <bool>(() => rootPathDirectoryInfo.Exists && rootPathDirectoryInfo.GetFileSystemInfos("*", SearchOption.AllDirectories).Length == 0); if (!_skipPathOption.HasValue() && rootPathCheck() || !_skipPathOption.HasValue() && _tryRunOption.HasValue()) { rootPathAction(rootPathDirectoryInfo, rootPathCheck); } } if (totalItems > 0) { var retryPolicy = Policy.Handle <Exception>().OrResult <bool>(r => r).WaitAndRetry(25, c => TimeSpan.FromMilliseconds(250)); var itemAction = new Action <string>(path => { if (_tryRunOption.HasValue()) { Thread.Sleep(1); } else { if (PathExtensions.IsDirectory(path)) { var di = new DirectoryInfo(path); retryPolicy.Execute(() => { di.Refresh(); if (di.Exists) { di.Attributes = FileAttributes.Normal; di.Delete(true); } di.Refresh(); return(di.Exists); }); } else { var fi = new FileInfo(path); retryPolicy.Execute(() => { fi.Refresh(); if (fi.Exists) { fi.Attributes = FileAttributes.Normal; fi.Delete(); } fi.Refresh(); return(fi.Exists); }); } } }); var rootPathAction = new Action <DirectoryInfo, Func <bool> >((di, check) => { if (_tryRunOption.HasValue()) { Thread.Sleep(1); } else { retryPolicy.Execute(() => { di.Refresh(); if (check()) { di.Attributes = FileAttributes.Normal; di.Delete(); } di.Refresh(); return(check()); }); } }); if (!_listItemsOption.HasValue() && !_quietOption.HasValue()) { ExecuteWithProgressBar(itemAction, rootPathAction); } else if (_listItemsOption.HasValue() && !_quietOption.HasValue()) { foreach (string path in items.OrderByDescending(x => x.Length)) { Console.WriteLine(path); } if (!_skipPathOption.HasValue()) { Console.WriteLine(matcher.RootPath); } } else if (!_listItemsOption.HasValue() && _quietOption.HasValue()) { ExecuteQuiet(itemAction, rootPathAction); } } stopwatch.Stop(); TimeSpan completeElapsed = stopwatch.Elapsed; if (_listItemsOption.HasValue() || _quietOption.HasValue()) { return(Task.FromResult(Ok)); } PrintSummary(totalItems, completeElapsed, getItemsElapsed); return(Task.FromResult(Ok)); }
public void ItShouldHandleShorterPathThenTheLimit(string path, int limit) { var ret = PathFormatter.ShrinkPath(path, limit); Assert.Equal(path, ret); }
public void ItShouldHandleInvalidInput(string path, int limit) { var ret = PathFormatter.ShrinkPath(path, limit); Assert.Equal(string.Empty, ret); }
public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); string localPath = Server.MapPath(savePath); try { #region 新增将附件上传到指定路径 2019-08-27 // 获取是否指定资源服务器路径 string resourceUrl = System.Configuration.ConfigurationManager.AppSettings.Get("EditorResourceUrl"); // 如果指定,就上传至指定路径 if (!string.IsNullOrWhiteSpace(resourceUrl)) { string rootPath = System.Configuration.ConfigurationManager.AppSettings.Get("EditorResource"); if (string.IsNullOrWhiteSpace(rootPath)) { rootPath = "C:\\Editor\\upload\\"; } localPath = rootPath + savePath.Replace("/", "\\"); savePath = resourceUrl + "/" + savePath; } #endregion if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; WriteUploadExLog(e.Message); } finally { WriteResult(); } }
public override void Process() { byte[] array = null; string text = null; int fileSize = 0; if (this.UploadConfig.Base64) { text = this.UploadConfig.Base64Filename; array = Convert.FromBase64String(base.Request[this.UploadConfig.UploadFieldName]); } else { HttpPostedFile httpPostedFile = base.Request.Files[this.UploadConfig.UploadFieldName]; text = httpPostedFile.FileName; if (!this.CheckFileType(text)) { this.Result.State = UploadState.TypeNotAllow; this.WriteResult(); return; } if (!this.CheckFileSize(httpPostedFile.ContentLength)) { this.Result.State = UploadState.SizeLimitExceed; this.WriteResult(); return; } fileSize = httpPostedFile.ContentLength; array = new byte[httpPostedFile.ContentLength]; try { httpPostedFile.InputStream.Read(array, 0, httpPostedFile.ContentLength); } catch (Exception) { this.Result.State = UploadState.NetworkError; this.WriteResult(); } } this.Result.OriginFileName = text; string text2 = PathFormatter.Format(text, this.UploadConfig.PathFormat); string path = base.Server.MapPath(text2); try { if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } GalleryHelper.AddPhote(Convert.ToInt32(base.Request.Form["cate_id"]), this.Result.OriginFileName, text2, fileSize, 0); File.WriteAllBytes(path, array); this.Result.Url = text2; this.Result.State = UploadState.Success; } catch (Exception ex2) { this.Result.State = UploadState.FileAccessError; this.Result.ErrorMessage = ex2.Message; } finally { this.WriteResult(); } }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; try { if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { var file = Request.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); #region 再需要储存文件到服务器 //if (!Directory.Exists(Path.GetDirectoryName(localPath))) //{ // Directory.CreateDirectory(Path.GetDirectoryName(localPath)); //} //File.WriteAllBytes(localPath, uploadFileBytes); //Result.Url = savePath; //Result.State = UploadState.Success; #endregion #region 旧代码 //IOClient target = new IOClient(); //var extra = new PutExtra(); //extra.MimeType = "text/plain"; //extra.Crc32 = 123; //extra.CheckCrc = CheckCrcType.CHECK; //extra.Params = new Dictionary<string, string>(); //var put = new PutPolicy("ctxsdhy-blog"); ////上传结束回调事件 //target.PutFinished += new EventHandler<PutRet>((o, e) => //{ //file.Del(); //if (e.OK) //{ // RSHelper.RSDel(Bucket, file.FileName); //} //}); //PutRet ret = target.PutFile(put.Token(), Guid.NewGuid().ToString(), localPath, extra); //直接通过二进制流上传 //PutRet ret = target.Put(put.Token(), Guid.NewGuid().ToString(), new MemoryStream(uploadFileBytes), extra); #endregion GetResult(uploadFileBytes); } catch (Exception e) { //Result.State = UploadState.FileAccessError; //Result.ErrorMessage = e.Message; GetResult(uploadFileBytes); } finally { WriteResult(); } }
public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); string date = DateTime.Now.ToString("yyyyMMdd"); string dir = Path.Combine(ConfigurationManager.AppSettings["UploadPath"], date); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } localPath = Path.Combine(dir, uploadFileName); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); if (Request["action"] == "uploadimage") { ImageResizeOptions imageResizeOptions = new ImageResizeOptions(); imageResizeOptions.cut = false; imageResizeOptions.Width = 640; imageResizeOptions.Height = 0; Result.Url = ConfigurationManager.AppSettings["UploadUrl"] + "/" + date + "/" + ImageManager.ResizeImage(localPath, imageResizeOptions); Result.State = UploadState.Success; } else { Result.Url = ConfigurationManager.AppSettings["UploadUrl"] + date + "/" + uploadFileName; Result.State = UploadState.Success; } } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } uploadFileName = Guid.NewGuid() + "_" + uploadFileName; Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); try { //FileHelper.UploadDocument(uploadFileBytes, savePath, DZAFCPortal.Config.AppSettings.SharePointSiteUrl); Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public override void Process() { byte[] array = null; string text = null; if (UploadConfig.Base64) { text = UploadConfig.Base64Filename; array = Convert.FromBase64String(base.Request[UploadConfig.UploadFieldName]); } else { HttpPostedFile httpPostedFile = base.Request.Files[UploadConfig.UploadFieldName]; text = httpPostedFile.FileName; if (!CheckFileType(text)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(httpPostedFile.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } array = new byte[httpPostedFile.ContentLength]; try { httpPostedFile.InputStream.Read(array, 0, httpPostedFile.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = text; string text2 = PathFormatter.Format(text, UploadConfig.PathFormat); string path = base.Server.MapPath(text2); try { if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } File.WriteAllBytes(path, array); Result.Url = text2; Result.State = UploadState.Success; } catch (Exception ex2) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = ex2.Message; } finally { WriteResult(); } }
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; HttpPostedFile file = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { file = Request.Files[UploadConfig.UploadFieldName]; uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = savePath; Result.State = UploadState.Success; if (UploadConfig.imageCompressEnable) { //裁剪边长 System.Drawing.Image originalImage = System.Drawing.Image.FromFile(localPath); string picfilename = Path.GetFileName(localPath); if (originalImage.Width > UploadConfig.imageCompressBorder) { originalImage.Dispose(); string temppath = Server.MapPath("/data/images/temp/" + picfilename); if (!Directory.Exists(Path.GetDirectoryName(temppath))) { Directory.CreateDirectory(Path.GetDirectoryName(temppath)); } File.WriteAllBytes(temppath, uploadFileBytes); Base.Utils.MakeThumbnail(temppath, localPath, UploadConfig.imageCompressBorder, 10000, "W"); } //生成缩略图 string thumbPath = "/data/images_thumb/" + DateTime.Now.ToString("yyyyMM"); thumbPath = HttpContext.Current.Server.MapPath(thumbPath); if (!Directory.Exists(thumbPath)) { Directory.CreateDirectory(thumbPath); } string thumbfile = thumbPath + "/" + Path.GetFileName(localPath); Base.Utils.MakeThumbnail(localPath, thumbfile, 100, 80, "WH"); } } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; // string path = "upload/" + uploadFileName; // //"E:\\PublishTmpPath\\"; //Server.MapPath(savePath); var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = ConfigurationManager.AppSettings["filepath"] + savePath; var urlPath = ConfigurationManager.AppSettings["uploaduri"] + savePath; try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = urlPath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
/// <summary> /// 保存文件 /// </summary> /// <returns></returns> private ResponseBaseModel <dynamic> PutFile() { var resultMode = new ResponseBaseModel <dynamic> { ResultCode = ResponceCodeEnum.Success, Message = "响应成功" }; if (Request.Files.Count < 1) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "文件不能为空"; return(resultMode); } var file = Request.Files[0]; var uploadFileName = file?.FileName; if (string.IsNullOrEmpty(uploadFileName)) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "文件不能为空"; return(resultMode); } var fileExtension = Path.GetExtension(uploadFileName).ToLower(); var headImageType = AppConfigurationHelper.GetString("headImageType", null) ?? ".png,.jpg,.gif,.jpeg"; if (!headImageType.Split(',').Select(x => x.ToLower()).Contains(fileExtension)) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "文件类型只能为.png,.jpg,.gif,.jpeg"; return(resultMode); } //默认2M var imageMaxSize = AppConfigurationHelper.GetInt32("imageMaxSize", 0) <= 0 ? 2048000 : AppConfigurationHelper.GetInt32("imageMaxSize", 0); if (imageMaxSize < file.ContentLength) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "文件大小不能超过2M"; return(resultMode); } var uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "文件读取失败"; return(resultMode); } //文件保存路径 //"imagePathFormat": "/Uploadfile/ShareDetailImage/{yyyy}{mm}{dd}/{time}{rand:6}" var imagePathFormat = AppConfigurationHelper.GetString("imagePathFormat", null); imagePathFormat = string.IsNullOrEmpty(imagePathFormat) ? "/Uploadfile/ShareDetailImage/{yyyy}{mm}{dd}/{time}{rand:6}" : imagePathFormat; var savePath = PathFormatter.Format(uploadFileName, imagePathFormat); var localPath = Server.MapPath(savePath); if (string.IsNullOrEmpty(localPath)) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "文件保存路径创建失败"; return(resultMode); } try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } System.IO.File.WriteAllBytes(localPath, uploadFileBytes); resultMode.Message = savePath; resultMode.ResultCode = ResponceCodeEnum.Success; } catch (Exception) { resultMode.ResultCode = ResponceCodeEnum.Fail; resultMode.Message = "文件读取失败"; } return(resultMode); }
public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Server.MapPath(savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } MemoryStream ms = new MemoryStream(uploadFileBytes); Image imageThumb; imageThumb = ImageUtility.MakeThumbnail(null, ms, localPath, 900, 225, "W", 1); if (imageThumb != null) { uploadFileBytes = ImageHelper.ImageToBytes(Image.FromFile(localPath)); } //File.WriteAllBytes(localPath, uploadFileBytes);不存原图 ArticleImages image = new ArticleImages() { ImageContent = uploadFileBytes, ImageName = savePath }; BaseService <ArticleImages> ser = new BaseService <ArticleImages>("CAAdmin"); ser.Repository.Insert(image); Result.Url = "/Common/File?id=" + image.Id + "&FileName=" + image.ImageName; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
private static bool Equals(Subpath subpath1, Subpath subpath2) { return(PathFormatter.ToString(subpath1) == PathFormatter.ToString(subpath2)); }
public override void Process() { 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(uploadFileName)) { Result.state = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.state = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.state = UploadState.NetworkError; WriteResult(); } } Result.original = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.url = savePath; Result.state = UploadState.Success; } catch (Exception e) { Result.state = UploadState.FileAccessError; Result.message = e.Message; } finally { WriteResult(); } }
public ActionResult UploadFile(string fileType) { string callback = Request["callback"]; UploadResult result = new UploadResult() { State = UploadState.Unknown }; UEditorModel uploadConfig = new UEditorModel(); if (fileType == "uploadimage") { uploadConfig = new UEditorModel() { AllowExtensions = UEditorConfig.GetStringList("imageAllowFiles"), PathFormat = UEditorConfig.GetString("imagePathFormat"), SizeLimit = UEditorConfig.GetInt("imageMaxSize"), UploadFieldName = UEditorConfig.GetString("imageFieldName") }; } if (fileType == "uploadscrawl") { uploadConfig = new UEditorModel() { AllowExtensions = new string[] { ".png" }, PathFormat = UEditorConfig.GetString("scrawlPathFormat"), SizeLimit = UEditorConfig.GetInt("scrawlMaxSize"), UploadFieldName = UEditorConfig.GetString("scrawlFieldName"), Base64 = true, Base64Filename = "scrawl.png" }; } if (fileType == "uploadvideo") { uploadConfig = new UEditorModel() { AllowExtensions = UEditorConfig.GetStringList("videoAllowFiles"), PathFormat = UEditorConfig.GetString("videoPathFormat"), SizeLimit = UEditorConfig.GetInt("videoMaxSize"), UploadFieldName = UEditorConfig.GetString("videoFieldName") }; } if (fileType == "uploadfile") { uploadConfig = new UEditorModel() { AllowExtensions = UEditorConfig.GetStringList("fileAllowFiles"), PathFormat = UEditorConfig.GetString("filePathFormat"), SizeLimit = UEditorConfig.GetInt("fileMaxSize"), UploadFieldName = UEditorConfig.GetString("fileFieldName") }; } byte[] uploadFileBytes; string uploadFileName; if (uploadConfig.Base64) { uploadFileName = uploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[uploadConfig.UploadFieldName]); } else { var file = Request.Files[uploadConfig.UploadFieldName]; uploadFileName = file.FileName; var fileExtension = Path.GetExtension(uploadFileName).ToLower(); if (!uploadConfig.AllowExtensions.Select(x => x.ToLower()).Contains(fileExtension)) { result.State = UploadState.TypeNotAllow; return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript")); } if (!(file.ContentLength < uploadConfig.SizeLimit)) { result.State = UploadState.SizeLimitExceed; return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript")); } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { result.State = UploadState.NetworkError; return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript")); } } result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, uploadConfig.PathFormat); var localPath = Server.MapPath(savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } System.IO.File.WriteAllBytes(localPath, uploadFileBytes); result.Url = savePath; result.State = UploadState.Success; } catch (Exception e) { result.State = UploadState.FileAccessError; result.ErrorMessage = e.Message; } return(Content(WriteUploadResult(callback, result), string.IsNullOrWhiteSpace(callback) ? "text/plain" : "application/javascript")); }
public override UEditorResult Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]); } else { #if NETSTANDARD2_0 var file = Request.Form.Files[UploadConfig.UploadFieldName]; #endif #if NET35 var file = Request.Files[UploadConfig.UploadFieldName]; #endif uploadFileName = file.FileName; if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; return(WriteResult()); } #if NETSTANDARD2_0 if (!CheckFileSize(file.Length)) #endif #if NET35 if (!CheckFileSize(file.ContentLength)) #endif { Result.State = UploadState.SizeLimitExceed; return(WriteResult()); } #if NETSTANDARD2_0 uploadFileBytes = new byte[file.Length]; try { file.OpenReadStream().Read(uploadFileBytes, 0, (int)file.Length); } #endif #if NET35 uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } #endif catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); var localPath = Path.Combine(Config.WebRootPath, savePath); UEditorResult result; try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { result = WriteResult(); } return(result); }
public override void Process() { string str; byte[] numArray; if (this.UploadConfig.Base64) { str = this.UploadConfig.Base64Filename; numArray = Convert.FromBase64String(this.Request[this.UploadConfig.UploadFieldName]); } else { HttpPostedFile file = this.Request.Files[this.UploadConfig.UploadFieldName]; str = file.FileName; if (!this.CheckFileType(str)) { this.Result.State = UploadState.TypeNotAllow; this.WriteResult(); return; } if (!this.CheckFileSize(file.ContentLength)) { this.Result.State = UploadState.SizeLimitExceed; this.WriteResult(); return; } numArray = new byte[file.ContentLength]; try { file.InputStream.Read(numArray, 0, file.ContentLength); } catch (Exception ex) { this.Result.State = UploadState.NetworkError; this.WriteResult(); } } this.Result.OriginFileName = str; string path1 = PathFormatter.Format(str, this.UploadConfig.PathFormat); string path2 = this.Server.MapPath(path1); try { if (!Directory.Exists(Path.GetDirectoryName(path2))) { Directory.CreateDirectory(Path.GetDirectoryName(path2)); } File.WriteAllBytes(path2, numArray); this.Result.Url = path1; this.Result.State = UploadState.Success; } catch (Exception ex) { this.Result.State = UploadState.FileAccessError; this.Result.ErrorMessage = ex.Message; } finally { this.WriteResult(); } }
public override void Process() { 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(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; var savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat, out string error); if (!string.IsNullOrEmpty(error) && error != "SUCCESS") { Result.State = UploadState.FileAccessError; Result.ErrorMessage = error; } var localPath = Server.MapPath(savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public override void Process() { byte[] uploadFileBytes = null; //文件原名 string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request[UploadConfig.UploadFieldName]); } else { //提交**的表单名称UploadConfig.UploadFieldName var file = Request.Files[UploadConfig.UploadFieldName];//json中 Config.GetString("imageFieldName") uploadFileName = file.FileName; //检查文件类型限制 if (!CheckFileType(uploadFileName)) { Result.State = UploadState.TypeNotAllow; WriteResult(); return; } //检查文件大小限制 if (!CheckFileSize(file.ContentLength)) { Result.State = UploadState.SizeLimitExceed; WriteResult(); return; } uploadFileBytes = new byte[file.ContentLength]; try { //将文件流写入uploadFileBytes中 file.InputStream.Read(uploadFileBytes, 0, file.ContentLength); } catch (Exception) { Result.State = UploadState.NetworkError; WriteResult(); } } Result.OriginFileName = uploadFileName; //文件保存路径"imagePathFormat": "/Content/upfile/{yyyy}{mm}{dd}/{time}{rand:6}", string savePath = PathFormatter.Format(uploadFileName, UploadConfig.PathFormat); //转换为绝对路径 string localPath = Server.MapPath(savePath); try { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } //1.0 将文件保存到本地路径中 File.WriteAllBytes(localPath, uploadFileBytes); //2.0 再上传至七牛,之后就一直用七牛的地址 string bucket = System.Configuration.ConfigurationManager.AppSettings["QiNiuBucket"]; string qiniuUrlIndex = System.Configuration.ConfigurationManager.AppSettings["QiNiuURL"]; string key = UploadConfig.QiniuPathFormat + DateTime.Now.ToString("yyyyMMdd") + "/" + localPath.Split('\\').Last(); bool qiniuFlag = ZYN.BLOG.WebHelper.QiniuHelper.UploadFile(bucket, key, localPath); if (qiniuFlag) { //3.0 为了节省服务器存储空间,保存至七牛后,将服务器文件删除。 string dir = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "Content\\upfile"; Directory.Delete(dir, true); //4.0 先将新上传的文章文件(图片和文件等)入库->(便于页面中链接的展示)->保存完或更新完文章后补全文件的FromArticleId #region 自定义: 开始把上传的图片信息临时存入Session;用于保存文章时获取文章内文件信息 StaticFile artFile = new StaticFile() { FileRawName = uploadFileName, FileNowName = localPath.Split('\\').Last(), //FileLocalPath = null, FileOnLineURL = qiniuUrlIndex + "/" + key, //保存到库中的均为真实路径 //FromArticleId = null, //添加完文章之后再赋值 FileType = 1, UploadTime = DateTime.Now }; ZYN.BLOG.IBLL.IStaticFileService fileService = ZYN.BLOG.WebHelper.OperateHelper.Current.serviceSession.StaticFileService; int val = fileService.Add(artFile); //先将其入库,拿到Id再补全FromArticleId if (val == 1) { HttpContext context = HttpContext.Current; HttpSessionState session = context.Session; List <StaticFile> filelist = session["ArticleFiles"] as List <StaticFile>; if (filelist == null) { filelist = new List <StaticFile>(); session["ArticleFiles"] = filelist; } filelist.Add(artFile); } //如果动作是上传图片,就在页面中直接显示,如果动作是上传文件,就给Controller下载路由(不行,文章保存后,才保存的文件。那能不能先保存文件到数据库,后期再把这些文件的FromArticleId补上,我看行) if (UploadConfig.ActionName == "uploadimage") { Result.Url = qiniuUrlIndex + "/" + key; } else if (UploadConfig.ActionName == "uploadfile") { if (val == 1) { //为了防止图标显示不正确,配合ueditor.all.js中的文件图标函数getFileIcon 加上.pdf Result.Url = "http://www.zynblog.com/Admin/FileHandler/DownLoadFile?fileId=" + artFile.Id; Result.Url += "&fileName=" + uploadFileName; } else { Result.Url = qiniuUrlIndex + "/" + key; } } Result.State = UploadState.Success; #endregion } else { Result.Url = ""; Result.State = UploadState.NetworkError; Result.ErrorMessage = "上传至本地成功,但是上传至七牛失败(可能是没有网络)"; string dir = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "Content\\upfile"; Directory.Delete(dir, true); } } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }