从httppostedfile将二进制文件保存到blob

时间:2012-08-11 20:31:58

标签: file-upload azure binary blob

有人可以提供代码将上传的文件保存到二进制文件中的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

由于

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

六年后,似乎Dennis Burton's的答案与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);
}