Problem
When using the .NET SDK to upload a file from a MemoryStream, the upload operation may succeed, but the resulting file in OSS has a size of 0 bytes. This issue occurs because writing data to the MemoryStream moves the file pointer to the end of the stream.
Solution
-
Before passing the stream to the upload method, reset the file pointer to the beginning of the stream by calling
mStream.Seek(0, SeekOrigin.Begin);.public static void MemStreamUpload() { Uri endPoint = new Uri("http://oss-cn-beijing.aliyuncs.com"); string accessKeyID = "your_access_key_id"; string accessKeySecret = "your_access_key_secret"; string bucketName = "your_bucket_name"; string key = "ossobject.jpg"; string filepath = @"D:\1.jpg"; ObjectMetadata metadata = new ObjectMetadata(); // You can set custom metadata. metadata.UserMetadata.Add("myfield", "test"); OssClient ossClient = new OssClient(endPoint, accessKeyID, accessKeySecret); MemoryStream mStream = new MemoryStream(); Image image = Image.FromFile(filepath); image.Save(mStream, ImageFormat.Jpeg); mStream.Seek(0, SeekOrigin.Begin); PutObjectResult putObjectResult = ossClient.PutObject(bucketName, key, mStream, metadata); Console.WriteLine(putObjectResult.ETag); } -
Verify that the uploaded file has the correct size.