public static Format ( string originFileName, string pathFormat ) : string | ||
originFileName | string | |
pathFormat | string | |
Résultat | string |
public override void Process() { byte[] uploadFileBytes = null; string uploadFileName = null; Stream fileStream = 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); fileStream = file.InputStream; } 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); // var key = OssHelper.PutObject(fileStream, savePath); // Result.Url = "http://img.yoopoon.com/"+ key; // 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 = 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 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[] 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(); } }
/// <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() { 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 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; UEditorResult result; if (Config.GetBool("UseOss")) {//使用OSS存储 2019-10-16 try { string extension = Path.GetExtension(Path.GetFileName(uploadFileName)); var key = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(10000, 99999) + extension; Result.Url = Config.GetString("OssViewBaseUrl") + key; OssApiHelper ossApiHelper = new OssApiHelper(); using (Stream streams = new MemoryStream(uploadFileBytes)) { streams.Seek(0, SeekOrigin.Begin); var result1 = ossApiHelper.PutObject(key, streams); if (result1.Code == 0) { Result.State = UploadState.Success; } else { Result.State = UploadState.FileAccessError; Result.ErrorMessage = "Upload Oss Error:" + result1.Message; } } } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { result = WriteResult(); } } else { 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 { result = WriteResult(); } } return(result); }
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 Crawler Fetch() { if (!IsExternalIPAddress(this.SourceUrl)) { State = "INVALID_URL"; return(this); } var request = HttpWebRequest.Create(this.SourceUrl) as HttpWebRequest; using (var response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { State = "Url returns " + response.StatusCode + ", " + response.StatusDescription; return(this); } if (response.ContentType.IndexOf("image") == -1) { State = "网址不是一个图像 "; return(this); } string strTypeCode = ""; Dal.Models.TemplateInfo tempInfo = (Dal.Models.TemplateInfo)Context.Session["TemplateInfo"]; if (tempInfo == null) { strTypeCode = Dal.Models.FileType.NoticeImage.ToString(); } else { if (tempInfo.PartCode == "Appendix") { strTypeCode = Dal.Models.FileType.DeclarationAppendix.ToString(); } else if (tempInfo.PartCode == "Atlas") { strTypeCode = Dal.Models.FileType.DeclarationAtlas.ToString(); } else { strTypeCode = Dal.Models.FileType.DeclarationImage.ToString(); } } ServerUrl = PathFormatter.Format(strTypeCode, Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat")); var savePath = Server.MapPath(ServerUrl); if (!Directory.Exists(Path.GetDirectoryName(savePath))) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } try { 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 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 = string.Empty; switch (UploadConfig.UploadParams) { case "UploadImgForNoticeShowBg": path = System.Configuration.ConfigurationManager.AppSettings["NoticeImgShowBgPath"]; break; case "UploadImgForSchoolStyle": path = System.Configuration.ConfigurationManager.AppSettings["SchoolStylePath"]; break; case "UploadImgForAdvertContent": path = System.Configuration.ConfigurationManager.AppSettings["AdvertImgContentPath"]; break; case "UploadImgForLinkContent": path = System.Configuration.ConfigurationManager.AppSettings["LinkImgContentPath"]; break; case "UploadImgForMessageContent": path = System.Configuration.ConfigurationManager.AppSettings["MessageImgContentPath"]; break; case "UploadWordForContent": path = System.Configuration.ConfigurationManager.AppSettings["WordContentPath"]; break; } var savePath = PathFormatter.Format(uploadFileName, path + 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; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }
public override void Process() { byte[] buffer = null; string filename = null; int fileSize = 0; if (this.UploadConfig.Base64) { filename = this.UploadConfig.Base64Filename; buffer = Convert.FromBase64String(base.Request[this.UploadConfig.UploadFieldName]); } else { HttpPostedFile file = base.Request.Files[this.UploadConfig.UploadFieldName]; filename = file.FileName; if (!this.CheckFileType(filename)) { this.Result.State = UploadState.TypeNotAllow; this.WriteResult(); return; } if (!this.CheckFileSize(file.ContentLength)) { this.Result.State = UploadState.SizeLimitExceed; this.WriteResult(); return; } fileSize = file.ContentLength; buffer = new byte[file.ContentLength]; try { file.InputStream.Read(buffer, 0, file.ContentLength); } catch (Exception) { this.Result.State = UploadState.NetworkError; this.WriteResult(); } } this.Result.OriginFileName = filename; string path = PathFormatter.Format(filename, this.UploadConfig.PathFormat); string str3 = base.Server.MapPath(path); try { if (!Directory.Exists(Path.GetDirectoryName(str3))) { Directory.CreateDirectory(Path.GetDirectoryName(str3)); } GalleryHelper.AddPhote(Globals.RequestFormNum("cate_id"), this.Result.OriginFileName, path, fileSize); File.WriteAllBytes(str3, buffer); this.Result.Url = path; this.Result.State = UploadState.Success; } catch (Exception exception) { this.Result.State = UploadState.FileAccessError; this.Result.ErrorMessage = exception.Message; } finally { this.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); } String fileExt = Path.GetExtension(this.SourceUrl).ToLower(); int len = fileExt.LastIndexOf('?'); if (len != -1) { fileExt = fileExt.Substring(0, len); // Guid.NewGuid().ToString().Replace("-",""); ServerUrl = PathFormatter.Format($"{Guid.NewGuid().ToString().Replace("-", "")}{fileExt}", Config.GetString("catcherPathFormat")); } else { ServerUrl = PathFormatter.Format(Path.GetFileName(this.SourceUrl), Config.GetString("catcherPathFormat")); } var savePath = Path.Combine(Config.WebRootPath, ServerUrl); if (!Directory.Exists(Path.GetDirectoryName(savePath))) { Directory.CreateDirectory(Path.GetDirectoryName(savePath)); } try { 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 CrawlerViewModel Crawler( Repository repository, string siteName, MediaFolder folder, string[] source, string catcherPathFormat) { var result = new CrawlerViewModel { state = "SUCCESS" }; if (source == null || source.Length == 0) { result.state = "参数错误:没有指定抓取源"; return(result); } result.list = source.Select(item => { var crawler = new CrawlerItemViewModel(); if (!IsExternalIPAddress(item)) { crawler.state = "INVALID_URL"; return(crawler); } crawler.source = item; var request = HttpWebRequest.Create(item) as HttpWebRequest; using (var response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { crawler.state = "Url returns " + response.StatusCode + ", " + response.StatusDescription; return(crawler); } if (response.ContentType.IndexOf("image") == -1) { crawler.state = "Url is not an image"; return(crawler); } try { var name = Path.GetFileName(item); if (!Path.HasExtension(item)) { name += ".jpg"; } var fileName = PathFormatter.Format(name, catcherPathFormat); var stream = response.GetResponseStream(); var reader = new BinaryReader(stream); 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); } ms.Flush(); var res = Upload(repository, siteName, folder, fileName, ms); crawler.url = res.url; } crawler.state = "SUCCESS"; } catch (Exception e) { crawler.state = "抓取错误:" + e.Message; } return(crawler); } return(crawler); }); return(result); }
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); } }
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(); } }
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); 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; 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 UEditorResult Process() { byte[] uploadFileBytes = null; string uploadFileName = null; if (UploadConfig.Base64) { uploadFileName = UploadConfig.Base64Filename; uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]); } else { #if net462 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 net462 if (!CheckFileSize(file.Length)) #endif #if NET35 if (!CheckFileSize(file.ContentLength)) #endif { Result.State = UploadState.SizeLimitExceed; return(WriteResult()); } #if net462 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 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 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; 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(AppDomain.CurrentDomain.BaseDirectory, savePath); try { if (UploadConfig.IsLocal) { if (!Directory.Exists(Path.GetDirectoryName(localPath))) { Directory.CreateDirectory(Path.GetDirectoryName(localPath)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = savePath; Result.State = UploadState.Success; } else { FileHandler fTPHelper = new FileHandler(); MemoryStream stream = new MemoryStream(uploadFileBytes); FileHandler.FileServiceResult result = fTPHelper.UploadFile(stream, UploadConfig.FileServerUrl, savePath); Result.Url = result.Data[0]; 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(); } }
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(); } }
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)); } File.WriteAllBytes(localPath, uploadFileBytes); Result.Url = Regex.Replace(savePath, "/UploadRoot/", "/", RegexOptions.IgnoreCase); 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(); } } 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); //自动存素材处理 //IAttachmentsItemService _attachmentsItemService = EngineContext.Current.Resolve<IAttachmentsItemService>(); //AttachmentsItemPostProperty p = new AttachmentsItemPostProperty() //{ // SaveFullName = savePath, // ServerPath = Server.MapPath("~/"), // FileName = System.IO.Path.GetFileName(savePath), // TargetFilePath = savePath.Replace(System.IO.Path.GetFileName(savePath), ""), // UploadFileType = Request["action"].Replace("upload",""), // AppId = int.Parse(Request["appid"]), // Description = System.IO.Path.GetFileNameWithoutExtension(uploadFileName), // // VideoCoverSrc = Request["videoCoverSrc"] == null ? string.Empty : Request["videoCoverSrc"].Trim('/'), // //UserName =Request.User.Identity.Name, // //ViewId = pid, //}; //_attachmentsItemService.ThumbImageAndInsertIntoDB(p); string host = CommonService.GetSysConfig("Content Server", ""); Result.Url = host + savePath; Result.State = UploadState.Success; } catch (Exception e) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = e.Message; } finally { WriteResult(); } }