将文件上传至Azure Blob Storage

3
我希望能够异步地将文件上传到Azure Blob存储。我已经尝试了官方SDK中提供的方法:
这是我获取容器的方式:
public static class BlobHelper
{
    public static CloudBlobContainer GetBlobContainer()
    {
        // Pull these from config
        var blobStorageConnectionString = ConfigurationManager.AppSettings["BlobStorageConnectionString"];
        var blobStorageContainerName = ConfigurationManager.AppSettings["BlobStorageContainerName"];

        // Create blob client and return reference to the container
        var blobStorageAccount = CloudStorageAccount.Parse(blobStorageConnectionString);
        var blobClient = blobStorageAccount.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference(blobStorageContainerName);
        container.CreateIfNotExists();
        container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
        return container;
    }
}

这是我尝试上传文件的方式:

var documentName = Guid.NewGuid().ToString();

CloudBlobContainer container = BlobHelper.GetBlobContainer();

CloudBlockBlob blockBlob = container.GetBlockBlobReference(documentName);

public class FilesService
{
    public async Task<string> UploadFiles(HttpContent httpContent)
    {

        var documentName = Guid.NewGuid().ToString();

        CloudBlobContainer container = BlobHelper.GetBlobContainer();

        CloudBlockBlob blockBlob = container.GetBlockBlobReference(documentName);

        using (var fileStream = System.IO.File.OpenRead(@"path\myfile"))
        {
            await blockBlob.UploadFromStreamAsync(fileStream);
        }

        return blockBlob.Uri.ToString();
    }
}

问题是我不知道如何获取我的文件路径(它是由用户上传的)。
当我尝试这样做时:
var rootpath =  HttpContext.Current.Server.MapPath("~/App_Data");

var streamProvider = new MultipartFileStreamProvider(rootpath);

await httpContent.ReadAsMultipartAsync(streamProvider);
foreach (var file in streamProvider.FileData)
{
    var localName = file.LocalFileName;
    using (var fileStream = System.IO.File.OpenRead(file.LocalFileName))
    {
        await blockBlob.UploadFromStreamAsync(fileStream);
    }
}

当我尝试进行POST请求时,请求会崩溃并且没有返回任何内容(甚至是异常);
解决方法:
问题通过以下方式得到解决。我使用了一个服务方法来上传文件集合。

Service Method to upload a collection of blobs

BlobHelper 类中,我保存了关于容器所需的信息,然后实例化它,这是一个 static 类。使用集合可以将多个文件作为同一流的一部分上传。

我正在尝试通过获取文件路径来上传文件! - StefanL19
请问您能否分享一下针对上述问题的可工作代码片段?谢谢。 - Sampath
我将把它作为问题的扩展添加进去。 - StefanL19
仍然不清楚这段代码片段发生了什么问题:await httpContent.ReadAsMultipartAsync(streamProvider); - Sampath
该服务中的代码片段将上传文件。 - StefanL19
1个回答

3

我认为您正在尝试使用标准的ASP.NET方法和本地上下文获取上传到Blob Storage的文件路径。上传到Blob的文件将无法通过这种方式访问。

看起来您已经成功地上传了Blob。如果您的文件上传成功,您的方法应该返回blockBlob.Uri.ToString(),这是您文件的链接 - 您可以将其存储在数据库或任何其他地方。


是的,但问题在于请求没有到达URI部分。当执行ReadAsMultipartAsync时,它会立即崩溃。 - StefanL19
@StefanL19 我创建了 聊天室 - 如果你有时间,让我们聊聊看能否解决这个问题。 - Alex Belotserkovskiy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接