public bool Exist(string path) { try { return(client.DoesObjectExist(BucketName, path.TrimStart('/'))); } catch (Exception ee) { logger.Error("DoesObjectExist Error:" + ee); } return(false); }
/// <summary> /// 文件是否存在 /// </summary> /// <param name="key">文件唯一标识</param> /// <returns></returns> public bool CheckIfFileExist(string key) { try { bool exist = _ossClient.DoesObjectExist(_bucketName, key); return(exist); } catch (Exception ex) { throw new Exception(ex.ToString()); } }
public async Task <bool> ObjectsExistsAsync(string bucketName, string objectName) { if (string.IsNullOrEmpty(bucketName)) { throw new ArgumentNullException(nameof(bucketName)); } if (string.IsNullOrEmpty(objectName)) { throw new ArgumentNullException(nameof(objectName)); } return(await Task.FromResult(_client.DoesObjectExist(bucketName, objectName))); }
/// <summary> /// 是否存在 /// </summary> /// <param name="key">要获取的文件在OSS上的名称</param> /// <returns></returns> public bool IsExistObject(string key) { try { return(_ossClient.DoesObjectExist(_bucketName, key)); } catch (Exception ex) { LoggerFactory.CreateLoger().Warning("Aliyun DoesObjectExist failed, {0}", ex.Message); return(false); } }
public Uri ReadNotCreate(string container, string fileName, System.IO.Stream stream, bool lowercaseUri = true) { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException("path is required"); } if (stream == null) { throw new ArgumentNullException("stream"); } if (stream.CanSeek) { stream.Seek(0, System.IO.SeekOrigin.Begin); } Uri uri; try { fileName = fileName.ToLower(); var exist = client.DoesObjectExist(bucketName, fileName); if (!exist) { var putObjectRequest = new PutObjectRequest(bucketName, fileName, stream); putObjectRequest.StreamTransferProgress += streamProgressCallback; client.PutObject(putObjectRequest); } string path = string.Empty; if (string.IsNullOrEmpty(cdnUrl)) { path = string.Format("https://{0}.{1}/{2}", bucketName, endpoint, fileName); } else { path = string.Format("https://{0}/{1}", cdnUrl, fileName); } uri = new Uri(path, UriKind.Absolute); } #pragma warning disable CS0168 // 声明了变量“e”,但从未使用过 catch (Exception e) #pragma warning restore CS0168 // 声明了变量“e”,但从未使用过 { throw; } return(uri); }
public Task <bool> ExistsAsync(string path) { if (String.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } try { return(Task.FromResult(_client.DoesObjectExist(_bucket, NormalizePath(path)))); } catch (Exception ex) when(IsNotFoundException(ex)) { return(Task.FromResult(false)); } }
public (bool isExist, string fileUrl) IsObjectExist(string bucketName, string objectName) { if (string.IsNullOrWhiteSpace(bucketName)) { throw new FException($"bucketName不能为空"); } if (string.IsNullOrWhiteSpace(objectName)) { throw new FException($"objectName不能为空"); } bool isExist = _ossClient.DoesObjectExist(bucketName, objectName); string fileUrl = isExist ? $"https://{bucketName}.{Endpoint}/{objectName}" : string.Empty; return(isExist : isExist, fileUrl : fileUrl); }
/// <summary> /// Check Existence of the specified identifier. /// </summary> /// <param name="identifier">The storage identifier.</param> /// <returns><c>true</c> if existed, <c>false</c> otherwise.</returns> public override bool Exists(BinaryStorageIdentifier identifier) { try { identifier.CheckNullObject(nameof(identifier)); if (!string.IsNullOrWhiteSpace(identifier.Container)) { return(client.DoesObjectExist(identifier.Container, identifier.Identifier)); } } catch (Exception ex) { throw ex.Handle(identifier); } return(false); }
public static void DoesObjectExist(string bucketName) { const string key = "key1"; try { var exist = client.DoesObjectExist(bucketName, key); Console.WriteLine("exist ? " + exist); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } }
/// <summary> /// 检查bucket是否存在 /// </summary> /// <param name="bucketName">bucket名</param> /// <param name="key">key文件key</param> /// <param name="ossPoint">站点</param> /// <param name="accessId">accessId</param> /// <param name="accessKey">accessKey</param> /// <returns></returns> public static bool CheckFile(string bucketName, string key) { if (string.IsNullOrWhiteSpace(bucketName)) { throw new Exception("Bucket名称为空"); } //建立Oss客户端连接 OssClient client = ConnOssClient(); //网络连接中取出key if (key.ToLower().StartsWith("http")) { string tempKey = key.Replace("://", ""); key = tempKey.Substring(tempKey.IndexOf("/") + 1); } return(client.DoesObjectExist(bucketName, key)); }
public async override Task <UploadFileResult> UploadFileAsync(Stream stream, string fileName = null, string savePath = null) { var client = new OssClient(aliSettings.BucketEndpoint, aliSettings.AK, aliSettings.SK); try { var dayPath = DateTime.Today.ToString("yyyy/MM/dd"); var saveKey = string.IsNullOrWhiteSpace(savePath) ? $"{dayPath}/{fileName}" : $"{savePath}/{fileName}"; if (client.DoesObjectExist(aliSettings.DefaultBucket, saveKey)) { var uploadObjectMd5 = OssUtils.ComputeContentMd5(stream, stream.Length); var existObjectMd5 = client.GetObjectMetadata(aliSettings.DefaultBucket, saveKey).ContentMd5; if (uploadObjectMd5 != existObjectMd5) { saveKey = string.IsNullOrWhiteSpace(savePath) ? $"{dayPath}/{StringUtilities.GenerateString(16, containsUpperCase: false, containsSpecialChar: false)}-{fileName}" : $"{savePath}/{StringUtilities.GenerateString(16, containsUpperCase: false, containsSpecialChar: false)}-{fileName}"; } } var uploadResult = client.PutObject(aliSettings.DefaultBucket, saveKey, stream); if (uploadResult.HttpStatusCode == System.Net.HttpStatusCode.OK) { var fileUrl = $"{aliSettings.FileUrlPrefix.TrimEnd('/')}/{saveKey}"; return(new UploadFileResult { Status = 1, Message = $"File upload successfully.", FileName = fileName, FileUrl = fileUrl }); } return(await Task.FromResult(new UploadFileResult { Status = 0, Message = "File upload failed.", FileName = fileName })); } catch (Exception ex) { Console.WriteLine($"UploadFileAsync ERROR:{ex.Message}"); return(new UploadFileResult { Status = 0, Message = $"File upload failed. Error Message:{ex.Message}", FileName = fileName }); } }
public static void DoesObjectExist(string bucketName, string key) { const string accessId = "<your access id>"; const string accessKey = "<your access key>"; const string endpoint = "<valid host name>"; var client = new OssClient(endpoint, accessId, accessKey); try { var exist = client.DoesObjectExist(bucketName, key); Console.WriteLine("exist ? " + exist); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } }
/// <summary> /// 直接从云服务器上取图片 /// </summary> /// <param name="key"></param> public static void GetObject(string key, Image img) { try { if (client.DoesObjectExist(Config.bucketName, key)) { var result = client.GetObject(Config.bucketName, key); using (var requestStream = result.Content) { using (var fs = File.Open(Config.DirToDownload + key.GetHashCode(), FileMode.OpenOrCreate)) { int length = 4 * 1024; var buf = new byte[length]; do { length = requestStream.Read(buf, 0, length); fs.Write(buf, 0, length); } while (length != 0); AsyncImageDownload.Instance.SetAsyncImage(key, img); } } Debug.Log("Get object succeeded"); } } catch (OssException ex) { Debug.Log("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}" + ex.ErrorCode + ex.Message + ex.RequestId + ex.HostId); } catch (Exception ex) { Debug.Log("-------Failed with error info: {0}" + ex.Message); } }
public bool ExistKey(string bucketName, string filename) { return(client.DoesObjectExist(bucketName, filename)); }
private void UploadFile(string localFileName) { var eTag = Class1.GenerateMD5WithFilePath(localFileName); var req = new http._Oss.GetSTSInfoReq() { UserId = Class1.UserId }; var resp = http._Oss.GetSTSInfo(req); Thread t = new Thread(new ThreadStart(() => { // 拿到STS临时凭证后,通过其中的安全令牌(SecurityToken)和临时访问密钥(AccessKeyId和AccessKeySecret)生成OSSClient。 var client = new OssClient(Class1.EndPoint, resp.AccessKeyId, resp.AccessKeySecret, resp.SecurityToken); if (!client.DoesObjectExist(Class1.BucketName, eTag)) { try { using (var fs = File.Open(localFileName, FileMode.Open)) { var putObjectRequest = new PutObjectRequest(Class1.BucketName, eTag, fs); putObjectRequest.StreamTransferProgress += UploadProgressCallback; client.PutObject(putObjectRequest); } Console.WriteLine("Put object:{0} succeeded", eTag); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } } Invoke(new Action(() => { pgb_upload.Value = 100; pgb_upload.Visible = false; })); var name = Path.GetFileName(localFileName); var createObjectReq = new http._Object.CreateObjectReq() { ETag = eTag, Name = name }; var createObjectResp = http._Object.CreateObject(createObjectReq); var objId = createObjectResp.Id; Class1.InsertObjectIfNotExists(objId, eTag, name); var sendMessageReq = new http._Message.SendMessageReq() { UserIdSend = Class1.UserId, IdRecv = userIdChat, Content = objId.ToString(), ContentType = (int)Class1.ContentType.Object, MessageType = 0 }; var sendMessageResp = http._Message.SendMessage(sendMessageReq); var statusCode = sendMessageResp.StatusCode; switch (statusCode) { case 1: { Class1.appendSysMsgToMsgBox(this, "你与" + $"{Class1.UserId2User[userIdChat].NickName}({userIdChat})" + "未成为好友,无法发送消息", DateTime.Now); return; } } var messageId = sendMessageResp.Id; var createTime = sendMessageResp.CreateTime; var param = Class1.Gzip(System.Text.Encoding.Default.GetBytes(objId.ToString())); var ret = Class1.sql.ExecuteNonQueryWithBinary($"INSERT INTO `message`(id, user_id_send, user_id_recv, group_id, content, create_time, content_type, msg_type) VALUES({messageId}, " + $"{Class1.UserId}, {userIdChat}, 0, @param, {createTime}, {(int)Class1.ContentType.Object}, 0)", param); if (!ret) { MessageBox.Show("DB错误,INSERT INTO message失败", "信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } Class1.appendFileToMsgBox(this, $"{Class1.UserId2User[Class1.UserId].NickName}({Class1.UserId})", Class1.StampToDateTime(createTime), "[文件]" + name, objId); })); t.Start(); }
public static void UploadImage(string localFileName, long groupId, frm_group frmGroup) { var eTag = Class1.GenerateMD5WithFilePath(localFileName); var req = new http._Oss.GetSTSInfoReq() { UserId = Class1.UserId }; var resp = http._Oss.GetSTSInfo(req); Thread t = new Thread(new ThreadStart(() => { // 拿到STS临时凭证后,通过其中的安全令牌(SecurityToken)和临时访问密钥(AccessKeyId和AccessKeySecret)生成OSSClient。 var client = new OssClient(Class1.EndPoint, resp.AccessKeyId, resp.AccessKeySecret, resp.SecurityToken); if (!client.DoesObjectExist(Class1.BucketName, eTag)) { try { using (var fs = File.Open(localFileName, FileMode.Open)) { var putObjectRequest = new PutObjectRequest(Class1.BucketName, eTag, fs); //putObjectRequest.StreamTransferProgress += UploadProgressCallback; client.PutObject(putObjectRequest); } Console.WriteLine("Put object:{0} succeeded", eTag); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } } var name = Path.GetFileName(localFileName); var sendMessageReq = new http._Message.SendMessageReq() { UserIdSend = Class1.UserId, IdRecv = groupId, Content = eTag, ContentType = (int)Class1.ContentType.Image, MessageType = (int)Class1.MsgType.GroupChat }; var sendMessageResp = http._Message.SendMessage(sendMessageReq); var statusCode = sendMessageResp.StatusCode; switch (statusCode) { case 1: { cls_group.appendSysMsgToMsgBox(frmGroup, "你尚未加入群聊,无法发送消息", DateTime.Now); return; } } var messageId = sendMessageResp.Id; var createTime = sendMessageResp.CreateTime; var param = Class1.Gzip(System.Text.Encoding.Default.GetBytes(eTag)); var ret = Class1.sql.ExecuteNonQueryWithBinary($"INSERT INTO `message`(id, user_id_send, user_id_recv, group_id, content, create_time, content_type, msg_type) VALUES({messageId}, " + $"{Class1.UserId}, 0, {groupId}, @param, {createTime}, {(int)Class1.ContentType.Image}, {(int)Class1.MsgType.GroupChat})", param); if (!ret) { MessageBox.Show("DB错误,INSERT INTO message失败", "信息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } var imageData = Class1.LoadFile(localFileName); var imageParam = Class1.Gzip(imageData); Class1.InsertImageIfNotExists(eTag, imageParam); cls_group.appendImageToMsgBox(frmGroup, Class1.UserId.ToString(), Class1.StampToDateTime(createTime), imageData); })); t.Start(); }
public bool Exists(FileId id) { return(_OssClient.DoesObjectExist(_BucketName, id.ToString())); }
public void MutUpload(BackgroundWorker worker, List <string> localPath, string remoteRootPath, string localRootPath) { //相同操作 bool sameOp = false; //是否覆盖 bool IsOver = false; List <string> NoSuccessList = new List <string>(); List <string> skipList = new List <string>(); int totalCount = localPath.Count; int currentCount = 0; foreach (string localFilePath in localPath) { string fileName = Path.GetFileName(localFilePath); if (!string.IsNullOrEmpty(localRootPath))//如果是文件夹,则包含原有路径 { fileName = Path.GetFileName(localRootPath) + "/" + fileName; } string remoteFilePath = remoteRootPath.TrimStart('/') + fileName; currentCount++; int pgPresent = (int)((double)currentCount / totalCount * 100); //显示总进度 worker.ReportProgress(pgPresent, new ProgressState() { CurrentTitle = fileName, CurrentCount = currentCount }); #region 是否存在 if (!sameOp) { bool exsitFile = client.DoesObjectExist(BucketName, remoteFilePath); if (exsitFile) { SureDialog myDialog = new SureDialog(); MyShowDialogResult myDR = new MyShowDialogResult(); myDialog.ShowDialog(fileName, myDR); sameOp = myDR.IsCheck; IsOver = myDR.Result; if (!myDR.Result) { worker.ReportProgress(pgPresent, new ProgressState() { ListBoxMsg = fileName + " 跳过 " }); skipList.Add(fileName); continue; } } } else { bool exsitFile = client.DoesObjectExist(BucketName, remoteFilePath); if (exsitFile) { if (!IsOver) { worker.ReportProgress(pgPresent, new ProgressState() { ListBoxMsg = fileName + "跳过 " }); skipList.Add(fileName); continue; } } } #endregion #region 单个文件 bool singleResult = false; try { client.PutObject(BucketName, remoteFilePath, localFilePath); singleResult = true; } catch (Exception ee) { singleResult = false; logger.Error("upload Error:" + ee); } #endregion //显示单个上传结果 string msg = string.Format("{0} 上传{1}", fileName, singleResult ? "成功" : "失败"); worker.ReportProgress(pgPresent, new ProgressState() { ListBoxMsg = msg }); if (!singleResult) { NoSuccessList.Add(fileName); } } }
public bool Exists(OssClient client) { TkDebug.AssertArgumentNull(client, "client", this); return(client.DoesObjectExist(BucketName, ObjectName)); }