public void CheckLoginInfo(OperatorInfo optorInfo) { upYun = new UpYun(optorInfo.bucketName, optorInfo.operatorName, optorInfo.operatorPwd); upYun.setApiDomain(StrFormatUtil.FormatNetStr(optorInfo.netSelection)); try { double useSpace = upYun.getBucketUsage(); SFUSetting.Save(); SFULogger.DEFAULT.InfoFormat("操作员[{0}]登录成功.BucketName=[{1}],APINet=[{2}],BucketUsage=[{3}]", optorInfo.operatorName, optorInfo.bucketName, optorInfo.netSelection, useSpace); } catch (Exception ex) { upYun = null; if (ex.Message.Contains("401")) { string exceptionMsg = String.Format("操作员[{0}]登录失败.原因:登录信息填写有误,BucketName=[{1}],APINet=[{2}],ExceptionMsg=[{3}]", optorInfo.operatorName, optorInfo.bucketName, optorInfo.netSelection, ex); LoginException loginException = new LoginException(401, exceptionMsg); SFULogger.DEFAULT.Error(loginException.Message); throw loginException; } else { string exceptionMsg = String.Format("操作员[{0}]登录失败.原因:未知,BucketName=[{1}],APINet=[{2}],ExceptionMsg=[{3}]", optorInfo.operatorName, optorInfo.bucketName, optorInfo.netSelection, ex); LoginException loginException = new LoginException(0, exceptionMsg); SFULogger.DEFAULT.Error(loginException.Message); throw loginException; } } }
public void UpYunTest() { WebSiteConfig postgreSQLConfig = ConfigManager.GetPostgreSQLConfig(); UpYun upyun = new UpYun(postgreSQLConfig.upyunBucket, postgreSQLConfig.upyunUsername, postgreSQLConfig.upyunPassword); ArrayList str = upyun.readDir("/"); foreach (var item in str) { Console.WriteLine(item); } }
public object Upload(byte[] uploadFileBytes, string uploadFileName) { object model; try { string fileMd5 = UpYun.BytesMd5(uploadFileBytes); string bucket = "panpan"; // 空间名称 string username = "******"; // 操作员 string password = "******"; // 密码 UpYun upyun = new UpYun(bucket, username, password); // 设置待上传文件的 Content-MD5 值(如又拍云服务端收到的文件MD5值与用户设置的不一致,将回报 406 Not Acceptable 错误) //upyun.setContentMD5(fileMd5); upyun.ContentMd5 = fileMd5; // 上传文件时可使用 upyun.writeFile("/a/test.jpg",postArray, true); // 进行父级目录的自动创建(最深10级目录) string upYunFilePath = string.Format("{0}/{1}{2}", this.UpYunPath, fileMd5, Path.GetExtension(uploadFileName)); bool success = upyun.WriteFile(upYunFilePath, uploadFileBytes, true); if (success) { // 返回图片在UpYun中的http访问地址 Result.Url = string.Format("{0}{1}", "http://static.qpanpan.cn", upYunFilePath); Result.State = UploadState.Success; } else { Result.State = UploadState.FileAccessError; Result.ErrorMessage = "上传图片到又拍云失败"; Logger.Error(Result.ErrorMessage); } } catch (Exception err) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = err.Message; Logger.Error(Result.ErrorMessage); } finally { model = new { state = GetStateMessage(Result.State), url = Result.Url, title = Result.OriginFileName, original = Result.OriginFileName, error = Result.ErrorMessage }; } return(model); }
public void CreatTokenTest() { WebSiteConfig postgreSQLConfig = ConfigManager.GetPostgreSQLConfig(); UpYun upyun = new UpYun("bucket", "username", "password"); upyun.secret = postgreSQLConfig.upyunSecret;; Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; unixTimestamp += 120; string _upt = upyun.CreatToken(unixTimestamp.ToString(), upyun.secret, $"/upload/debbb8740a597ca554d194818af6e560/270a9d65cfb903fb89cb21c78bd6bad106b543ca.jpg"); Console.WriteLine($"https://upyun.morenote.top/upload/debbb8740a597ca554d194818af6e560/270a9d65cfb903fb89cb21c78bd6bad106b543ca.jpg?_upt={_upt}"); }
public static bool DeleteImage(string path, ApplicationKeyType applicationKeyType) { string valueByCache = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiYunOperaterName"); string password = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiOperaterPassword"); string bucketname = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiSpaceName"); string oldValue = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiPhotoDomain"); UpYun yun = new UpYun(bucketname, valueByCache, password); if (path.Contains("http://")) { path = path.Replace(oldValue, ""); path = path.StartsWith("/") ? path : ("/" + path); } return yun.deleteFile(path); }
public static string UploadExecute(byte[] buffer, string FileName, ApplicationKeyType applicationKeyType) { string valueByCache = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiYunOperaterName"); string password = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiOperaterPassword"); string bucketname = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiSpaceName"); string str4 = ConfigSystem.GetValueByCache(applicationKeyType + "_YouPaiPhotoDomain"); UpYun yun = new UpYun(bucketname, valueByCache, password); byte[] data = buffer; string path = "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + FileName; if (yun.writeFile(path, data, true)) { return (str4 + path); } return ""; }
public async Task <IActionResult> EditAdminUser(AdminUserFormModel model, IFormFile headImg) { string headImgUrl = string.Empty; if (headImg?.Length > 1024 * 1024) { return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "上传的图片不能超过1MB", null))); } else if (headImg?.Length > 0) { //判断文件格式 string[] extArr = { ".jpg", ".png", ".gif", ".jpeg" }; string fileExt = Path.GetExtension(headImg.FileName); if (!extArr.Contains(fileExt)) { return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "选择的图片中包含不支持的格式", null))); } //计算文件的MD5值并拼接文件路径 string fileMd5 = GetMd5Hash(headImg.OpenReadStream()); string fileName = $"{fileMd5}{fileExt}"; DateTime now = DateTime.Now; string fullPath = $"/uploadFile/{now.Year}/{now.Month}/{now.Day}/{fileName}"; //文件上传至又拍云中 UpYun upYun = new UpYun { Operator = "rentalsite", Password = "******" }; byte[] fileByteArr = StreamToBytes(headImg.OpenReadStream()); //Stream转换byte[] bool isOK = await upYun.WriteFileAsync(fileByteArr, fullPath); if (!isOK) { return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "文件上传失败", null))); } headImgUrl = $"https://aspnetweb.b0.upaiyun.com{fullPath}"; } model.HeadImgUrl = headImgUrl; string json = await PutAsync(model, _urlSettings.AdminUser.EditAdminUser); Response.StatusCode = JsonConvert.DeserializeObject <ResultModel>(json).Status; return(Content(json, "application/json", Encoding.UTF8)); }
public object UpLoad(string imageName, Stream imageStream) { object model; try { byte[] imageBytes = UpYun.StreamToBytes(imageStream); string upYunFilePath = string.Format("/images/qrcode/{0}", imageName); UpYun upYun = new UpYun("panpan", "panpan", "panpan88") { ContentMd5 = UpYun.BytesMd5(imageBytes), }; bool success = upYun.WriteFile(upYunFilePath, imageBytes, true); if (success) { // 返回图片在UpYun中的http访问地址 Result.Url = "http://static.qpanpan.cn" + upYunFilePath; Result.State = UploadState.Success; } else { Result.State = UploadState.FileAccessError; Result.ErrorMessage = "上传图片到又拍云失败"; Logger.Error(Result.ErrorMessage); } } catch (Exception ex) { Result.State = UploadState.FileAccessError; Result.ErrorMessage = ex.Message; Logger.Error(Result.ErrorMessage); } finally { model = new { state = GetStateMessage(Result.State), url = Result.Url, title = Result.OriginFileName, original = Result.OriginFileName, error = Result.ErrorMessage }; } return(model); }
/// <summary> /// 文件上传 /// </summary> /// <param name="stream">文件流</param> /// <param name="ext">文件扩展名</param> /// <returns>是否上传成功;文件路径</returns> public static async Task <(bool, string)> FileUpload(byte[] buffer, string ext) { UpYun upYun = new UpYun { Operator = "rentalsite", Password = "******" }; //计算文件的MD5值并拼接文件路径 string fileMd5 = GetMd5Hash(buffer); string fileName = $"{fileMd5}{ext}"; DateTime now = DateTime.Now; string fullPath = $"/uploadFile/{now.Year}/{now.Month}/{now.Day}/{fileName}"; //文件上传至又拍云中 bool isOK = await upYun.WriteFileAsync(buffer, fullPath); return(isOK, fullPath); }
public JsonResult CreateQrCode(string content) { string url = null; try { QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.H); QrCode qrCode; bool ok = qrEncoder.TryEncode(content, out qrCode); if (ok) { GraphicsRenderer renderer = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White); using (MemoryStream stream = new MemoryStream()) { renderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream); UploadResult ur = new UploadResult() { State = UploadState.Unknown, OriginFileName = string.Format("{0}.png", UpYun.StreamMd5(stream)), }; ImageOperate imgOpe = new ImageOperate(ur); imgOpe.UpLoad(ur.OriginFileName, stream); url = ur.Url; } //string md5 = UpYun. } } catch (Exception ex) { url = null; logger.Error(ex); } return(Json(new { Status = (url == null) ? "error" : "ok", Url = url, })); }
public async Task <bool> SaveUploadFileOnUPYunAsync(UpYun upyun, IFormFile formFile, string uploadDirPath, string fileName) { if (formFile.Length > 0) { // string fileExt = Path.GetExtension(formFile.FileName); //文件扩展名,不含“.” // long? fileSize = formFile.Length; //获得文件大小,以字节为单位 if (!Directory.Exists(uploadDirPath)) { Directory.CreateDirectory(uploadDirPath); } var filePath = uploadDirPath + fileName; MemoryStream stmMemory = new MemoryStream(); await formFile.CopyToAsync(stmMemory).ConfigureAwait(false); byte[] imageBytes = stmMemory.ToArray(); return(upyun.WriteFile($"{uploadDirPath}{fileName}", imageBytes, true)); } else { return(false); } }
public JsonResult SaveImage(string image) { try { // 获取base64字符串 byte[] imgBytes = Convert.FromBase64String(image); string md5 = UpYun.BytesMd5(imgBytes); UploadResult ur = new UploadResult() { State = UploadState.Unknown, OriginFileName = string.Format("{0}.jpg", _random.Next(100000, 10000000)), }; UpYun upYun = new UpYun("panpan", "panpan", "panpan88") { ContentMd5 = md5, }; string file = string.Format("/12310720112/{0}.jpg", md5); upYun.WriteFile(file, imgBytes, true); return(Json(new { status = "ok", msg = "http://static.qpanpan.cn" + file, })); } catch (Exception ex) { return(Json(new { status = "error", msg = ex.Message, })); } }
public async Task <IActionResult> SavePic(long id) { //判断文件是否存在 var files = Request.Form.Files; if (!files.Any()) { return(Json(new ResultModel { Status = (int)HttpStatusCode.BadRequest, Message = "没有找到文件!" })); } List <KeyValuePair <string, string> > keyValuePairs = new List <KeyValuePair <string, string> >(); string[] extArr = { ".jpg", ".png", ".gif", ".jpeg", ".bmp" }; UpYun upYun = new UpYun { Operator = "rentalsite", Password = "******" }; string host = "https://aspnetweb.b0.upaiyun.com"; string[] urlArr = new string[2]; foreach (var file in files) { //判断文件后缀 string fileExt = Path.GetExtension(file.FileName); if (!extArr.Contains(fileExt)) { return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "选择的图片中包含不支持的格式", null))); } var(isOk, filePath) = await FileUpload(file.OpenReadStream(), fileExt); if (!isOk) { return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "文件上传失败", null))); } urlArr[0] = $"{host}{filePath}"; //创建缩略图并上传 byte[] buffer = default; using (Image <Rgba32> image = Image.Load(file.OpenReadStream())) using (MemoryStream memStream = new MemoryStream()) { image.Mutate(x => { x.Resize(image.Width / 3, image.Height / 3); }); image.SaveAsPng(memStream); buffer = memStream.GetBuffer(); (isOk, filePath) = await FileUpload(buffer, ".png"); if (!isOk) { return(Json(new ResultModel((int)HttpStatusCode.BadRequest, "文件上传失败", null))); } } urlArr[1] = $"{host}{filePath}"; keyValuePairs.Add(new KeyValuePair <string, string>("urls", string.Join(',', urlArr))); } //向服务端发送请求并返回结果 var response = await CommonHelper.HttpClient.PutAsync($"{ServerUrl}{_url.House.UploadPicture}/{id}", new FormUrlEncodedContent(keyValuePairs)); string json = await response.Content.ReadAsStringAsync(); ResultModel res = JsonConvert.DeserializeObject <ResultModel>(json); Response.StatusCode = res.Status; return(Content(json, "application/json", Encoding.UTF8)); }
public void Logout() { upYun = null; }