/// POST 方式上传对象 public void PostObject() { //.cssg-snippet-body-start:[post-object] try { string bucket = "examplebucket-1250000000"; //存储桶,格式:BucketName-APPID string key = "exampleobject"; //对象键 string srcPath = @"temp-source-file"; //本地文件绝对路径 PostObjectRequest request = new PostObjectRequest(bucket, key, srcPath); //设置进度回调 request.SetCosProgressCallback(delegate(long completed, long total) { Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total)); }); //执行请求 PostObjectResult result = cosXml.PostObject(request); //请求成功 Console.WriteLine(result.GetResultInfo()); } catch (COSXML.CosException.CosClientException clientEx) { //请求失败 Console.WriteLine("CosClientException: " + clientEx); } catch (COSXML.CosException.CosServerException serverEx) { //请求失败 Console.WriteLine("CosServerException: " + serverEx.GetInfo()); } //.cssg-snippet-body-end }
public async Task <bool> PutObjectAsync(string bucketName, string objectName, Stream data, CancellationToken cancellationToken = default) { byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return(bytes); } if (string.IsNullOrEmpty(bucketName)) { throw new ArgumentNullException(nameof(bucketName)); } if (string.IsNullOrEmpty(objectName)) { throw new ArgumentNullException(nameof(objectName)); } byte[] upload = StreamToBytes(data); if (upload == null || upload.Length == 0) { throw new Exception("Upload file stram is null."); } string contentType = "application/octet-stream"; if (data is FileStream fileStream) { string fileName = fileStream.Name; if (!string.IsNullOrEmpty(fileName)) { new FileExtensionContentTypeProvider().TryGetContentType(fileName, out contentType); } } if (string.IsNullOrEmpty(contentType)) { contentType = "application/octet-stream"; } bucketName = ConvertBucketName(bucketName); PostObjectRequest request = new PostObjectRequest(bucketName, objectName, upload); request.SetContentType(contentType); PostObjectResult result = _client.PostObject(request); return(await Task.FromResult(result.IsSuccessful())); }