有人可以提供代码将上传的文件保存到二进制文件中的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
由于
答案 0 :(得分:9)
此代码片段基于将照片推送到blob存储的生产应用程序。这种方法直接从HttpPostedFile中提取流,并将其直接交给客户端库以存储到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);
}