public string GetMetaTime(string a, string b) { string c; var client = new OssClient(FMD5list[13], FMD5list[14], FMD5list[15]); try { using (var fs = File.Open(a, FileMode.Open)) { // 获取文件元信息。 if (a == "") { var oldMeta = client.GetObjectMetadata("bf1report", b); c = oldMeta.ToString(); } else { var oldMeta = client.GetObjectMetadata("bf1report", a + "/" + b); c = oldMeta.ToString(); } } Console.WriteLine("C:" + c); return(c); } catch (Exception ex) { Console.WriteLine("Put object failed, {0}", ex.Message); return(c = ""); } }
private static List <PartETag> UploadPartCopys(String targetBucket, String targetObject, String sourceBucket, String sourceObject, String uploadId, int partSize) { var metadata = client.GetObjectMetadata(sourceBucket, sourceObject); var fileSize = metadata.ContentLength; var partCount = (int)fileSize / partSize; if (fileSize % partSize != 0) { partCount++; } var partETags = new List <PartETag>(); for (var i = 0; i < partCount; i++) { var skipBytes = (long)partSize * i; var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); var request = new UploadPartCopyRequest(targetBucket, targetObject, sourceBucket, sourceObject, uploadId) { PartSize = size, PartNumber = i + 1, BeginIndex = skipBytes }; var result = client.UploadPartCopy(request); partETags.Add(result.PartETag); } return(partETags); }
public static void SyncAppendObject(string bucketName) { const string key = "AppendObject"; long position = 0; ulong initCrc = 0; try { var metadata = client.GetObjectMetadata(bucketName, key); position = metadata.ContentLength; initCrc = ulong.Parse(metadata.Crc64); } catch (Exception) {} try { using (var fs = File.Open(fileToUpload, FileMode.Open)) { var request = new AppendObjectRequest(bucketName, key) { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position, InitCrc = initCrc }; var result = client.AppendObject(request); position = result.NextAppendPosition; initCrc = result.HashCrc64Ecma; Console.WriteLine("Append object succeeded, next append position:{0}", position); } // append object by using NextAppendPosition using (var fs = File.Open(fileToUpload, FileMode.Open)) { var request = new AppendObjectRequest(bucketName, key) { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position, InitCrc = initCrc }; var result = client.AppendObject(request); position = result.NextAppendPosition; Console.WriteLine("Append object succeeded too, next append position:{0}", position); } } 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); } }
public static void GetObjectBySignedUrlWithWebRequest(string bucketName, string key) { try { var metadata = client.GetObjectMetadata(bucketName, key); var etag = metadata.ETag; var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get); req.AddQueryParam("param1", "value1"); req.ContentType = "text/html"; req.ContentMd5 = etag; req.AddUserMetadata("mk1", "mv1"); req.ResponseHeaders.CacheControl = "No-Cache"; req.ResponseHeaders.ContentEncoding = "utf-8"; req.ResponseHeaders.ContentType = "text/html"; // Generates url signature for accessing specified object. var uri = client.GeneratePresignedUri(req); var webRequest = (HttpWebRequest)WebRequest.Create(uri); webRequest.ContentType = "text/html"; webRequest.Headers.Add(HttpRequestHeader.ContentMd5, etag); webRequest.Headers.Add("x-oss-meta-mk1", "mv1"); var resp = webRequest.GetResponse() as HttpWebResponse; var output = resp.GetResponseStream(); var bufferSize = 2048; var bytes = new byte[bufferSize]; try { using (StreamWriter outfile = new StreamWriter(fileToSave)) { var length = 0; do { length = output.Read(bytes, 0, bufferSize); outfile.Write(bytes); } while (length > 0); } output.Close(); Console.WriteLine("Get object by signatrue succeeded."); } catch (Exception ex) { Console.WriteLine("ex : " + ex.Message); } } 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> /// <returns></returns> public MessageRecorder <ObjectMetadata> GetObjectMetadata(string key) { var r = new MessageRecorder <ObjectMetadata>(); try { r.Value = _client.GetObjectMetadata(BucketName, key); return(r.Info("获取文件元数据成功")); } catch (Exception ex) { return(r.Error($"获取文件元数据失败. 原因:{ex.Message}")); } }
public static void RestoreArchiveObject(string bucketName, string key, bool waitUtilFinished = true, int maxWaitTimeInSeconds = 600) { RestoreObjectResult result = client.RestoreObject(bucketName, key); if (result.HttpStatusCode != HttpStatusCode.Accepted || !waitUtilFinished) { throw new OssException(result.RequestId + ", " + result.HttpStatusCode + " ,"); } while (maxWaitTimeInSeconds > 0) { var meta = client.GetObjectMetadata(bucketName, key); string restoreStatus = meta.HttpMetadata["x-oss-restore"] as string; if (restoreStatus != null && restoreStatus.StartsWith("ongoing-request=\"false\"", StringComparison.InvariantCultureIgnoreCase)) { break; } Thread.Sleep(1000); maxWaitTimeInSeconds--; } if (maxWaitTimeInSeconds == 0) { throw new TimeoutException(); } }
public static void ModifyObjectMeta(string bucketName) { const string key = "key1"; try { byte[] binaryData = Encoding.ASCII.GetBytes("forked from aliyun/aliyun-oss-csharp-sdk "); var stream = new MemoryStream(binaryData); client.PutObject(bucketName, key, stream); var oldMeta = client.GetObjectMetadata(bucketName, key); var newMeta = new ObjectMetadata() { ContentType = "application/msword", ExpirationTime = oldMeta.ExpirationTime, ContentEncoding = null, CacheControl = "" }; client.ModifyObjectMeta(bucketName, key, newMeta); Console.WriteLine("Modify object meta succeeded"); } 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); } }
public static void GetObjectPartly() { const string localFilePath = "<your localFilePath>"; const string bucketName = "<your bucketName>"; const string fileKey = "<your fileKey>"; const string accessId = "<your access id>"; const string accessKey = "<your access key>"; _client = new OssClient(accessId, accessKey); using (var fileStream = new FileStream(localFilePath, FileMode.OpenOrCreate)) { var bufferedStream = new BufferedStream(fileStream); var objectMetadata = _client.GetObjectMetadata(bucketName, fileKey); var fileLength = objectMetadata.ContentLength; const int partSize = 1024 * 1024 * 10; var partCount = CalPartCount(fileLength, partSize); for (var i = 0; i < partCount; i++) { var startPos = partSize * i; var endPos = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1; Download(bufferedStream, startPos, endPos, localFilePath, bucketName, fileKey); } bufferedStream.Flush(); } }
private void button1_Click(object sender, EventArgs e) { if (dataGridView1.RowCount != 0) { try { string o = ""; List <string> Text = new List <string>(); XmlDocument doc = new XmlDocument(); int index = dataGridView1.CurrentRow.Index; doc.Load("http://bf1report.oss-cn-beijing.aliyuncs.com/Data/" + dataGridView1.Rows[index].Cells[0].Value.ToString() + ".xml"); var client = new OssClient(a, b, c); var oldMeta = client.GetObjectMetadata("bf1report", "Data/" + dataGridView1.Rows[index].Cells[0].Value.ToString() + ".xml"); o = "Game:" + oldMeta.UserMetadata["gamebb"] + "\n"; XmlNodeList nodes = doc.SelectNodes("/ReportText/Evil"); foreach (XmlNode node in nodes) { o = o + node.InnerText + "\n"; } richTextBox1.Text = o; richTextBox1.SelectAll(); //全选 richTextBox1.Copy(); //复制 } catch { } } }
public MemoryStream GetObjectPartly(string bucketName, string key) { try { OssClient client = CommonHelper.CreateOssClient(); var memoryStream = new MemoryStream(); var objectMetadata = client.GetObjectMetadata(bucketName, key); var fileLength = objectMetadata.ContentLength; const int partSize = 1024 * 1024 * 10; var partCount = CalPartCount(fileLength, partSize); for (var i = 0; i < partCount; i++) { var startPos = partSize * i; var endPos = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1; Download(memoryStream, startPos, endPos, bucketName, key, client); } return(memoryStream); } catch (Exception) { _commonFun.AlertLongText("操作异常,请重试。-->NotifiMngViewModel"); return(null); } }
/// <inheritdoc/> public async Task <BlobFileInfo> GetBlobFileInfo(string containerName, string blobName) { try { return(await Task.Run(() => { var key = $"{containerName}/{blobName}"; var result = _ossClient.GetObjectMetadata(_cfg.BucketName, key); return new BlobFileInfo { Container = containerName, ETag = result.ETag, LastModified = result.LastModified, Name = blobName, Length = result.ContentLength, Url = string.Format(_baseUrl, containerName, blobName), ContentMD5 = result.ContentMd5, ContentType = result.ContentType }; })); } catch (Exception ex) { throw new StorageException(StorageErrorCode.PostError.ToStorageError(), new Exception(ex.ToString())); } }
/// <summary> /// 拷贝大文件 /// </summary> /// <param name="client"></param> /// <param name="sourceBucket">源空间</param> /// <param name="sourceKey">源文件</param> /// <param name="optBucket">目标空间</param> /// <param name="optKey">目标文件</param> /// <returns></returns> private CopyFileResultDto CopyBigFile(OssClient client, string sourceBucket, string sourceKey, string optBucket, string optKey) { var initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(optBucket, optKey); var result = client.InitiateMultipartUpload(initiateMultipartUploadRequest); var partSize = Core.Tools.GetPartSize(ChunkUnit.U4096K); var metadata = client.GetObjectMetadata(sourceBucket, sourceKey); var fileSize = metadata.ContentLength; var partCount = (int)fileSize / partSize; if (fileSize % partSize != 0) { partCount++; } // 开始分片拷贝。 var partETags = new List <PartETag>(); for (var i = 0; i < partCount; i++) { var skipBytes = (long)partSize * i; var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); // 创建UploadPartCopyRequest。可以通过UploadPartCopyRequest指定限定条件。 var uploadPartCopyRequest = new UploadPartCopyRequest(optBucket, optKey, sourceBucket, sourceKey, result.UploadId) { PartSize = size, PartNumber = i + 1, // BeginIndex用来定位此次上传分片开始所对应的位置。 BeginIndex = skipBytes }; // 调用uploadPartCopy方法来拷贝每一个分片。 var uploadPartCopyResult = client.UploadPartCopy(uploadPartCopyRequest); Console.WriteLine("UploadPartCopy : {0}", i); partETags.Add(uploadPartCopyResult.PartETag); } // 完成分片拷贝。 var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(optBucket, optKey, result.UploadId); // partETags为分片上传中保存的partETag的列表,OSS收到用户提交的此列表后,会逐一验证每个数据分片的有效性。全部验证通过后,OSS会将这些分片合成一个完整的文件。 foreach (var partETag in partETags) { completeMultipartUploadRequest.PartETags.Add(partETag); } var ret = client.CompleteMultipartUpload(completeMultipartUploadRequest); if (ret.HttpStatusCode == HttpStatusCode.OK) { return(new CopyFileResultDto(true, sourceKey, "success")); } return(new CopyFileResultDto(false, sourceKey, $"RequestId:{ret.RequestId},HttpStatusCode:{ret.HttpStatusCode}")); }
/// <summary> /// 获取文件长度 /// </summary> /// <param name="name"></param> /// <returns></returns> public long GetFileLength(string name) { OssClient client = new OssClient(m_endPoint, m_keyID, m_keySecret); var objectMetadata = client.GetObjectMetadata(m_bucket, name); var fileLength = objectMetadata.ContentLength; return(fileLength); }
public ValueTask <FileSystemEntry> ReadMetadataAsync(string filePath, CancellationToken cancellation = default) { ObjectMetadata fileMetadata = null; filePath = filePath?.Replace('\\', '/').TrimStart('/'); if (string.IsNullOrEmpty(filePath)) { // Root Folder return(new ValueTask <FileSystemEntry>(new FileSystemEntry { Attributes = FileAttributes.Normal | FileAttributes.Directory, Size = 0, Name = string.Empty })); } var client = new OssClient(_OssConfig.OssEndpoint, _OssConfig.AccessKeyId, _OssConfig.AccessKeySecret); if (filePath.EndsWith('/')) { if (_IsDirectory(filePath, client)) { return(new ValueTask <FileSystemEntry>(new FileSystemEntry { Attributes = FileAttributes.Normal | FileAttributes.Directory, Size = 0, Name = GetRelativeName(filePath) })); } } else { try { fileMetadata = client.GetObjectMetadata(_OssConfig.BucketName, filePath); return(new ValueTask <FileSystemEntry>(new FileSystemEntry { Attributes = FileAttributes.Normal, ModificationDate = fileMetadata.LastModified, Size = fileMetadata.ContentLength, Name = GetRelativeName(filePath) })); } catch { // No such file } if (fileMetadata == null) { if (_IsDirectory(filePath, client)) { return(new ValueTask <FileSystemEntry>(new FileSystemEntry { Attributes = FileAttributes.Normal | FileAttributes.Directory, Size = 0, Name = GetRelativeName(filePath) })); } } } return(default);
public async Task <BlobDescriptor> GetBlobDescriptorAsync(string containerName, string blobName) { try { return(await Task.Run(() => { var props = _ossClient.GetObjectMetadata(containerName, blobName); var userMeta = props.UserMetadata; return new BlobDescriptor { Name = blobName, Container = containerName, Url = _baseUrl + "/" + containerName + "/" + blobName, ContentType = props.ContentType, ContentMD5 = userMeta != null && userMeta.ContainsKey("ContentMD5") ? userMeta["ContentMD5"] : null, ETag = props.ETag, LastModified = props.LastModified, Length = props.ContentLength, }; })); } catch (Exception e) { if (e.IsOssStorageException()) { throw e.Convert(); } else { var webEx = e as WebException; if (webEx?.Status == System.Net.WebExceptionStatus.ProtocolError) { throw new StorageException(new StorageError() { Code = (int)StorageErrorCode.InvalidCredentials, Message = "访问被拒绝,请检查配置!" }, webEx); } } throw; } }
protected void Page_Load(object sender, EventArgs e) { byte[] buffer = new Byte[10000]; int length = 0; long dataToRead; int offset = 0; int count = 300000; var client = new OssClient("oss-cn-hangzhou-zjzwy01-d01-a.cloud.zj.gov.cn", "qAALhWQY2oMy1cwE", "1XfG1fugfUt8v3BfoYEnCuVHlGQrYA"); var _filePath = "迁云前数据库备份/套红正文.pdf"; try { dataToRead = client.GetObjectMetadata("oa-oss", _filePath).ContentLength; Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.ContentType = "application/pdf"; Response.AddHeader("Content-Length", dataToRead.ToString()); while (dataToRead > 0) { if (dataToRead < count) { count = (int)dataToRead; } buffer = Read(client, _filePath, offset, count); offset += count; if (Response.IsClientConnected) { Response.OutputStream.Write(buffer, 0, count); Response.Flush(); buffer = new Byte[count]; dataToRead = dataToRead - count; } else { dataToRead = -1; } } } catch (Exception ex) { Response.Write("Error : " + ex.StackTrace + ex.Message);; } finally { Response.End(); } }
public void GetObjectPartly(string objectKey, string folderPath, int partCount) { string filePath = folderPath + "\\" + objectKey.Substring(objectKey.LastIndexOf("/") + 1); using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate)) { var bufferedStream = new BufferedStream(fileStream); var objectMetadata = client.GetObjectMetadata(bucketName, objectKey); var fileLength = objectMetadata.ContentLength; long partSize = fileLength / partCount; for (var i = 0; i < partCount; i++) { var startPos = partSize * i; var endPos = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1; Download(bufferedStream, startPos, endPos, filePath, bucketName, objectKey); } bufferedStream.Flush(); } }
/// <summary> /// 追加上传 /// </summary> /// <param name="bucketName"></param> /// <param name="fileToUpload"></param> /// <returns></returns> public string SyncAppendObject(string bucketName, string fileToUpload) { string key = DateTime.Now.ToSerialNumber() + Path.GetExtension(fileToUpload); long position = 0; try { var metadata = client.GetObjectMetadata(bucketName, key); position = metadata.ContentLength; } catch (Exception) { } try { using (var fs = File.Open(fileToUpload, FileMode.Open)) { var request = new AppendObjectRequest(bucketName, key) { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position }; var result = client.AppendObject(request); position = result.NextAppendPosition; } // append object by using NextAppendPosition using (var fs = File.Open(fileToUpload, FileMode.Open)) { var request = new AppendObjectRequest(bucketName, key) { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position }; var result = client.AppendObject(request); position = result.NextAppendPosition; } } catch (OssException ex) { } catch (Exception ex) { } return(key); }
private FileMeta GetObjectMeta(string bucketName, string key) { var metaData = _ossClient.GetObjectMetadata(bucketName, key); return(new FileMeta { Path = key, Name = Path.GetFileName(key), Size = metaData.ContentLength, ETag = metaData.ETag, LastModified = metaData.LastModified, Crc64 = metaData.Crc64, Md5 = metaData.ContentMd5 }); }
//追加文件(防止添加重复相片) public static void AppendObject() { //第一次追加文件的时候,文件可能已经存在,先获取文件的当前长度,如果不存在,position为0,如果存在则不会添加进去 long position = 0; try { var client = new OssClient("oss-cn-shenzhen.aliyuncs.com", "LTAId7dsrQHujhU5", "O3nQOqai4yXrvGCKNbvgrKuU8f7U7p"); var metadata = client.GetObjectMetadata("flowera", "2.jpg"); position = metadata.ContentLength; } catch (Exception) { } try { var client = new OssClient("oss-cn-shenzhen.aliyuncs.com", "LTAId7dsrQHujhU5", "O3nQOqai4yXrvGCKNbvgrKuU8f7U7p"); using (var fs = File.Open("D:/Users/pc/Desktop/个人文件/AlbumProject/AlbumProject/Content/2.jpg", FileMode.Open)) { var request = new AppendObjectRequest("flowera", "2.jpg") { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position }; var result = client.AppendObject(request); // 设置下次追加文件时的position位置 position = result.NextAppendPosition; Console.WriteLine("Append object succeeded, next append position:{0}", position); } // 再次追加文件,这时候的position值可以从上次的结果中获取到 using (var fs = File.Open("D:/Users/pc/Desktop/个人文件/AlbumProject/AlbumProject/Content/2.jpg", FileMode.Open)) { var request = new AppendObjectRequest("flowera", "2.jpg") { ObjectMetadata = new ObjectMetadata(), Content = fs, Position = position }; var result = client.AppendObject(request); position = result.NextAppendPosition; Console.WriteLine("Append object succeeded, next append position:{0}", position); } } catch (Exception ex) { Console.WriteLine("Append object failed, {0}", ex.Message); } }
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 Task <FileSpec> GetFileInfoAsync(string path) { if (String.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } path = NormalizePath(path); try { var metadata = _client.GetObjectMetadata(_bucket, path); return(Task.FromResult(new FileSpec { Path = path, Size = metadata.ContentLength, Created = metadata.LastModified, Modified = metadata.LastModified })); } catch (Exception) { return(Task.FromResult((FileSpec)null)); } }
public static void getObjectBySignedUrl2() { const string accessKeyId = "<your access key id>"; const string accessKeySecret = "<your access key secret>"; const string endpoint = "<valid host name>"; const string bucketName = "<bucket name>"; const string key = "<object name>"; OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var metadata = client.GetObjectMetadata(bucketName, key); var etag = metadata.ETag; var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get); // Generates url signature for accessing specified object. var uri = client.GeneratePresignedUri(req); Console.WriteLine(uri.ToString()); OssObject ossObject = client.GetObject(uri); var file = File.Open("<file to hold object content>", FileMode.OpenOrCreate); Stream stream = ossObject.Content; byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); file.Write(bytes, 0, bytes.Length); } 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); } }
public static void GetObjectPartly(string bucketName) { client.PutObject(bucketName, key, Config.BigFileToUpload); string localFilePath = dirToDownload + "/sample.3.data"; using (var fileStream = new FileStream(localFilePath, FileMode.OpenOrCreate)) { var bufferedStream = new BufferedStream(fileStream); var objectMetadata = client.GetObjectMetadata(bucketName, key); var fileLength = objectMetadata.ContentLength; const int partSize = 1024 * 1024 * 10; var partCount = CalPartCount(fileLength, partSize); for (var i = 0; i < partCount; i++) { var startPos = partSize * i; var endPos = partSize * i + (partSize < (fileLength - startPos) ? partSize : (fileLength - startPos)) - 1; Download(bufferedStream, startPos, endPos, localFilePath, bucketName, key); } bufferedStream.Flush(); } }
/// <summary> /// Fetches the cloud meta. Returned object would only includes (md5, length, name, content type). /// </summary> /// <param name="identifier">The identifier.</param> /// <returns>Beyova.BinaryStorageMetaData.</returns> public override BinaryStorageMetaData FetchCloudMeta(BinaryStorageIdentifier identifier) { try { identifier.CheckNullObject(nameof(identifier)); identifier.Container.CheckEmptyString(nameof(identifier.Container)); identifier.Identifier.CheckEmptyString(nameof(identifier.Identifier)); var meta = client.GetObjectMetadata(identifier.Container, identifier.Identifier); var result = new BinaryStorageMetaData(identifier) { Hash = meta.ContentMd5, Length = meta.ContentLength, Name = meta.ContentDisposition, ContentType = meta.ContentType }; return(result); } catch (Exception ex) { throw ex.Handle(identifier); } }
void BBJC()//版本检测,用于检测服务器和本地版本是否有区别 { try { //服务器MD5获取 var cliente = new OssClient("oss-cn-beijing.aliyuncs.com", "LTAIjOoHVuoXjhf8", "zTuZWpU3hdd6cPT0oVcsOIpxGgxtpC"); var oldMeta = cliente.GetObjectMetadata("bf1report", "version/Version.xml"); FMD5bt = oldMeta.UserMetadata["bf1report"]; FMD5sj = oldMeta.UserMetadata["bf1report-updata"]; FMD5wb = oldMeta.UserMetadata["zh-en"]; FBB = double.Parse(oldMeta.UserMetadata["version"]); Console.WriteLine(FMD5bt); Console.WriteLine(FMD5sj); Console.WriteLine(FMD5wb); Console.WriteLine(FBB);//打印FMD5list数组 } catch { MessageBox.Show("尝试从服务器获取信息失败", "版本检测出现错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } //本地MD5获取 Console.WriteLine(FBB); Console.WriteLine(FBB == 0); if (FBB == 0) { BBXX.Text = "版本检测:[失败]无法连接到服务器"; B_WBGX.Visible = false; } else { BMD5sj = GetMD5("BF1Report-Updata.exe"); BMD5wb = GetMD5("Zh-En.xml"); if (BMD5sj == FMD5sj) { list[1] = 1; } else { list[1] = 0; } if (BMD5wb == FMD5wb) { list[2] = 1; } else { list[2] = 0; } for (int b = 1; b < 3; b++)//检测list数组中,是否包含0,如果包含,说明有文件不一致,此时出现更新文本按钮 { if (list[b] == 0) { WJ = "MD5不同步"; //Console.WriteLine("list-" + b + "的" + "MD5不同步,它的值为:"+ list[b]); } else//如果不包含0,说明无需更新 { //Console.WriteLine("list-" + b + "的" + "MD5同步,它的值为:"+ list[b]); } } if (FBB == BB & WJ == "MD5同步") { BBXX.Text = "版本检测:当前软件已是最新版本"; B_WBGX.Visible = false; } else if (FBB < BB & WJ == "MD5同步") { BBXX.Text = "版本检测:软件版本高于与现有版本,无需更新"; B_WBGX.Visible = false; } else if (FBB > BB & WJ != "MD5同步" | WJ == "MD5同步") { BBXX.Text = "版本检测:[有软件更新]最新版本:V" + FBB; B_WBGX.Text = "下载更新"; B_WBGX.Visible = true; } else if (FBB == BB | FBB < BB & WJ != "MD5同步") { BBXX.Text = "版本检测:[有文本更新]"; B_WBGX.Text = "更新文本"; B_WBGX.Visible = true; if (FMD5sj != BMD5sj) { BBXX.Text = "版本检测:[下载器有更新]"; B_WBGX.Visible = true; B_WBGX.Text = "更新"; } } } }
/// <summary> /// 文件拷贝,默认采用分片拷贝的方式 /// </summary> /// <param name="bucketName"></param> /// <param name="objectName"></param> /// <param name="destBucketName"></param> /// <param name="destObjectName"></param> /// <returns></returns> public async Task <bool> CopyObjectAsync(string bucketName, string objectName, string destBucketName, string destObjectName = null) { if (string.IsNullOrEmpty(bucketName)) { throw new ArgumentNullException(nameof(bucketName)); } if (string.IsNullOrEmpty(objectName)) { throw new ArgumentNullException(nameof(objectName)); } if (string.IsNullOrEmpty(destBucketName)) { destBucketName = bucketName; } if (string.IsNullOrEmpty(destObjectName)) { destObjectName = objectName; } var partSize = 50 * 1024 * 1024; // 创建OssClient实例。 // 初始化拷贝任务。可以通过InitiateMultipartUploadRequest指定目标文件元信息。 var request = new InitiateMultipartUploadRequest(destBucketName, destObjectName); var result = _client.InitiateMultipartUpload(request); // 计算分片数。 var metadata = _client.GetObjectMetadata(bucketName, objectName); var fileSize = metadata.ContentLength; var partCount = (int)fileSize / partSize; if (fileSize % partSize != 0) { partCount++; } // 开始分片拷贝。 var partETags = new List <PartETag>(); for (var i = 0; i < partCount; i++) { var skipBytes = (long)partSize * i; var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); // 创建UploadPartCopyRequest。可以通过UploadPartCopyRequest指定限定条件。 var uploadPartCopyRequest = new UploadPartCopyRequest(destBucketName, destObjectName, bucketName, objectName, result.UploadId) { PartSize = size, PartNumber = i + 1, // BeginIndex用来定位此次上传分片开始所对应的位置。 BeginIndex = skipBytes }; // 调用uploadPartCopy方法来拷贝每一个分片。 var uploadPartCopyResult = _client.UploadPartCopy(uploadPartCopyRequest); partETags.Add(uploadPartCopyResult.PartETag); } // 完成分片拷贝。 var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(destBucketName, destObjectName, result.UploadId); // partETags为分片上传中保存的partETag的列表,OSS收到用户提交的此列表后,会逐一验证每个数据分片的有效性。全部验证通过后,OSS会将这些分片合成一个完整的文件。 foreach (var partETag in partETags) { completeMultipartUploadRequest.PartETags.Add(partETag); } _client.CompleteMultipartUpload(completeMultipartUploadRequest); return(await Task.FromResult(true)); }
public void _DownLoadFile(object value) { OssObject ossobject = null; GetObjectRequest request = null; ObjectMetadata metadata; FileStream fs = null; int readline = 0; //当前读取的字节长度 long countlength = 0; //已经读取的字节 byte[] buffer = new byte[length]; //文件块 string bucket = "", fileKey = "", targetPath = ""; if (value is string[]) { bucket = ((string[])value)[0]; fileKey = ((string[])value)[1]; targetPath = ((string[])value)[2]; } else { return; } if (File.Exists(targetPath)) { try { File.Delete(targetPath); } catch (IOException ioEx) //文件正在使用中,不能删除。 { return; } } fs = new FileStream(targetPath, FileMode.Create); try { request = new Aliyun.OpenServices.OpenStorageService.GetObjectRequest(bucket, fileKey); ossobject = client.GetObject(request);//获取文件流 //获取需要下载文件的信息。 metadata = client.GetObjectMetadata(bucket, fileKey); while ((readline = ossobject.Content.Read(buffer, 0, length)) > 0) { fs.Write(buffer, 0, readline); countlength += readline; if (DownLoadProcessing != null) { DownLoadProcessing(Convert.ToDouble(countlength) / Convert.ToDouble(metadata.ContentLength)); } } } catch (Aliyun.OpenServices.ServiceException serviceEx) //下载过程中出现错误。 { } finally { ossobject.Dispose(); fs.Close(); } }
//mod 0:查看全部档案列表 //mod 1:查看没有申请删除的档案 //mod 2:查看申请删除的档案 public void ListObject(string a, string b, string c, int mod) { var client = new OssClient(a, b, c); ObjectListing result = null; string nextMarker = string.Empty; do { // 每页列举的文件个数通过maxKeys指定,超过指定数将进行分页显示。 var listObjectsRequest = new ListObjectsRequest("bf1report") { Marker = nextMarker, MaxKeys = 100 }; result = client.ListObjects(listObjectsRequest); Console.WriteLine("File:"); int count = 0; foreach (var summary in result.ObjectSummaries) { count += 1; //Match m = Regex.Match(summary.Key, "/.+/(?<name1>.*)xml"); //Match d = Regex.Match(summary.Key, "Data/.+/.*?"); Match x = Regex.Match(summary.Key, "(Data/(?<name1>[^/]*).xml)"); // Match dux = Regex.Match(summary.Key, "Data/.+/.+xml"); //Match dx = Regex.Match(summary.Key, "(Data/(?<FileName>[^/]*).xml)|(Data/(?<Folder>[^/]*)/(?<FileName>[^/]*).xml)"); //Console.WriteLine(dx.Groups["FileName"].Value); //GetMetaTime(dx.Groups["Folder"].Value, dx.Groups["FileName"].Value); //MOD模式 //if (mod == 0) //{ // var oldMeta = client.GetObjectMetadata("bf1report", "Data/" + x.Groups["name1"].Value.ToString() + ".xml"); // //listBox1.Items.Add(x.Groups["name1"].Value); // //fileName.Value = dx.Groups["FileName"].Value; // //dataGridView1.Rows.Add(row); // int index = dataGridView1.Rows.Add(); // dataGridView1.Rows[index].Cells[0].Value = x.Groups["name1"].Value;//HackName // dataGridView1.Rows[index].Cells[1].Value = oldMeta.UserMetadata["reportname"];//ReportName // dataGridView1.Rows[index].Cells[2].Value = oldMeta.UserMetadata["uuid"];//UUID // DateTime st = oldMeta.LastModified; // dataGridView1.Rows[index].Cells[3].Value = st.ToLocalTime();//UpTime // dataGridView1.Rows[index].Cells[4].Value = oldMeta.UserMetadata["gamebb"]; //} if (mod == 1) { if (x.Groups["name1"].Value.ToString() != "") { var oldMeta = client.GetObjectMetadata("bf1report", "Data/" + x.Groups["name1"].Value.ToString() + ".xml"); //listBox1.Items.Add(x.Groups["name1"].Value); //fileName.Value = dx.Groups["FileName"].Value; //dataGridView1.Rows.Add(row); if (oldMeta.UserMetadata["delappyly"] == "no") { int index = dataGridView1.Rows.Add(); dataGridView1.Rows[index].Cells[0].Value = x.Groups["name1"].Value; //HackName dataGridView1.Rows[index].Cells[1].Value = oldMeta.UserMetadata["reportname"]; //ReportName dataGridView1.Rows[index].Cells[2].Value = oldMeta.UserMetadata["uuid"]; //UUID DateTime st = oldMeta.LastModified; dataGridView1.Rows[index].Cells[3].Value = st.ToLocalTime(); //UpTime dataGridView1.Rows[index].Cells[4].Value = oldMeta.UserMetadata["gamebb"]; } } } else if (mod == 2) { if (x.Groups["name1"].Value.ToString() != "") { var oldMeta = client.GetObjectMetadata("bf1report", "Data/" + x.Groups["name1"].Value.ToString() + ".xml"); //listBox1.Items.Add(x.Groups["name1"].Value); //fileName.Value = dx.Groups["FileName"].Value; //dataGridView1.Rows.Add(row); if (oldMeta.UserMetadata["delappyly"] != "no") { int index = dataGridView1.Rows.Add(); dataGridView1.Rows[index].Cells[0].Value = x.Groups["name1"].Value; //HackName dataGridView1.Rows[index].Cells[1].Value = oldMeta.UserMetadata["reportname"]; //ReportName dataGridView1.Rows[index].Cells[2].Value = oldMeta.UserMetadata["uuid"]; //UUID DateTime st = oldMeta.LastModified; dataGridView1.Rows[index].Cells[3].Value = st.ToLocalTime(); //UpTime dataGridView1.Rows[index].Cells[4].Value = oldMeta.UserMetadata["gamebb"]; } } } } nextMarker = result.NextMarker; } while (result.IsTruncated); }
public static void getObjectBySignedUrl() { const string accessKeyId = "<your access key id>"; const string accessKeySecret = "<your access key secret>"; const string endpoint = "<valid host name>"; const string bucketName = "<bucket name>"; const string key = "<object name>"; OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var metadata = client.GetObjectMetadata(bucketName, key); var etag = metadata.ETag; var req = new GeneratePresignedUriRequest(bucketName, key, SignHttpMethod.Get); // Set optional properties(be blind to them usually) req.AddQueryParam("param1", "value1"); req.ContentType = "text/html"; req.ContentMd5 = etag; req.AddUserMetadata("mk1", "mv1"); req.AddUserMetadata("mk2", "mv2"); req.ResponseHeaders.CacheControl = "No-Cache"; req.ResponseHeaders.ContentEncoding = "utf-8"; req.ResponseHeaders.ContentType = "text/html"; // Generates url signature for accessing specified object. var uri = client.GeneratePresignedUri(req); Console.WriteLine(uri.ToString()); var webRequest = (HttpWebRequest)WebRequest.Create(uri); webRequest.ContentType = "text/html"; webRequest.Headers.Add(HttpRequestHeader.ContentMd5, etag); webRequest.Headers.Add("x-oss-meta-mk1", "mv1"); webRequest.Headers.Add("x-oss-meta-mk2", "mv2"); var resp = webRequest.GetResponse() as HttpWebResponse; var output = resp.GetResponseStream(); var bufferSize = 2048; var bytes = new byte[bufferSize]; try { var length = 0; do { length = output.Read(bytes, 0, bufferSize); // to do something with bytes... } while (length > 0); output.Close(); } catch (Exception ex) { Console.WriteLine("ex : " + ex.Message); } } 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); } }