9

有人可以提供代码以二进制形式将上传的文件保存到 azure blob 吗?我目前使用文本保存,它在大文件上非常慢,逐行读取/保存到 blob。

Private Function ReadFile(ByVal file As HttpPostedFile) As String
        Dim result As String = ""
        Dim objReader As New System.IO.StreamReader(file.InputStream)
        Do While objReader.Peek() <> -1
            result = result & objReader.ReadLine() & vbNewLine
        Loop
        Return result
    End Function

谢谢

4

2 回答 2

9

此代码片段基于将照片推送到 blob 存储的生产应用程序。这种方法直接从 HttpPostedFile 中提取流并将其直接传递给客户端库以存储到 blob 中。您应该根据您的应用程序改变一些事情:

  • blobName 可能需要适应。
  • 直到获取 blob 客户端的连接字符串应该被隔离到辅助类中
  • 同样,您可能需要基于您的业务逻辑的 blob 容器的帮助程序
  • 您可能不希望容器完全可公开访问。这只是为了向您展示如何执行此操作,如果您愿意的话
// assuming HttpPostedFile is in a variable called postedFile  
var contentType = postedFile.ContentType;
var streamContents = postedFile.InputStream;
var blobName = postedFile.FileName

var connectionString = CloudConfigurationManager.GetSetting("YOURSTORAGEACCOUNT_CONNECTIONSTRING");
var storageAccount = CloudStorageAccount.Parse(connectionString);
var blobClient = storageAccount.CreateCloudBlobClient();

var container = blobClient.GetContainerReference("YOURCONTAINERNAME");
container.CreateIfNotExist();
container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });

var blob = container.GetBlobReference(blobName);
blob.Properties.ContentType = contentType;
blob.UploadFromStream(streamContents);
于 2012-08-11T21:06:51.233 回答
0

6 年后, Dennis Burton 的答案似乎与 WindowsAzure.Storage v9.3.2 不兼容。

对我来说,这有效:

IFormFile postedFile = null;
var contentType = postedFile.ContentType;
var blobName = postedFile.FileName;

var connectionString = "YOURSTORAGEACCOUNT_CONNECTIONSTRING";
var storageAccount = CloudStorageAccount.Parse(connectionString);
var blobClient = storageAccount.CreateCloudBlobClient();

var container = blobClient.GetContainerReference("YOURCONTAINERNAME");
await container.CreateIfNotExistsAsync();

var blob = container.GetBlockBlobReference(blobName);
blob.Properties.ContentType = contentType;
using (var streamContents = postedFile.OpenReadStream())
{
    await blob.UploadFromStreamAsync(streamContents);
}
于 2018-11-27T09:38:16.473 回答