我尝试使用下面的代码将文件上传到azure blob容器,但是上传的文件已损坏。
<React.Fragment>
我该如何解决。
无法打开使用上述代码上传到blob的excel文件。
错误:
public async void UploadFile(Stream memoryStream, string fileName, string containerName)
{
try
{
memoryStream.Position = 0;
CloudBlockBlob file = GetBlockBlobContainer(containerName).GetBlockBlobReference(fileName);
file.Metadata["FileType"] = Path.GetExtension(fileName);
file.Metadata["Name"] = fileName;
await file.UploadFromStreamAsync(memoryStream).ConfigureAwait(false);
}
catch (Exception ex)
{
throw ex;
}
}
答案 0 :(得分:0)
由于在此方法之外实例化了流,所以我假设文件在此被处理并添加到流中,但是,这里您将流的位置返回到0,从而使文件无效。
答案 1 :(得分:0)
看来您的方法没有致命问题。我想您的Stream转换部分出错了。
这是我的代码:
using System;
using System.IO;
using Microsoft.WindowsAzure.Storage;
namespace ConsoleApp7
{
class Program
{
public static class Util
{
public async static void UploadFile(Stream memoryStream, string fileName, string containerName)
{
memoryStream.Position = 0;
var storageAccount = CloudStorageAccount.Parse("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
var blockBlob = storageAccount.CreateCloudBlobClient()
.GetContainerReference(containerName)
.GetBlockBlobReference(fileName);
blockBlob.UploadFromStreamAsync(memoryStream);
}
}
static void Main(string[] args)
{
//Open the file
FileStream fileStream = new FileStream("C:\\Users\\bowmanzh\\Desktop\\Book1.xlsx", FileMode.Open);
//Read the byte[] of File
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes,0,bytes.Length);
fileStream.Close();
//turn from byte[] to Stream
Stream stream = new MemoryStream(bytes);
Util.UploadFile(stream,"Book2.xlsx","test");
Console.WriteLine("Hello World!");
Console.ReadLine();
}
}
}
答案 2 :(得分:0)
首先,您确定文件已损坏吗?将MemoryStream
内容和博客都保存到本地文件中并进行比较。您也可以将MemoryStream内容保存到文件中并使用UploadFromFileAsync
。
要检查实际损坏情况,您应该预先计算内容的MD5哈希值,并将其与上传后的Blob哈希值进行比较。
要计算流的MD5哈希值,请使用ComputeHash。
var hasher=MD5.Create();
memoryStream.Position = 0;
var originalHash=Convert.ToBase64String(hasher.ComputeHash(memoryStream));
要让客户端计算Blob,您需要在上传时设置BlobRequestOptions.StoreBlobContentMD5选项:
memoryStream.Position = 0;
var options = new BlobRequestOptions()
{
StoreBlobContentMD5 = testMd5
};
await file.UploadFromStreamAsync(memoryStream,null,options,null).ConfigureAwait(false);
要获取并检查上传的哈希,请使用FetchAttributes
或FetchAttributesAsync并将BlobProperties.ContentMD5的值与原始值进行比较:
file.FetchAttributes();
var blobHash=file.Properties.ContentMD5;
if (blobHash != originalHash)
{
//Ouch! Retry perhaps?
}
答案 3 :(得分:0)
您的上面的代码创建一个.csv文件,而不是.xlsx文件。您可以通过创建类似于您的代码构建内容的东西来轻松地对此进行测试,例如:
然后,如果将其重命名为.xlsx,以复制您所做的操作,则会得到:
您有两种解决方案:
或
您将其上传到Azure Blob存储的事实在这里完全不相关-上传没有问题。