问题出现在 GetBlobReferenceFromServer 上 - 我从 Azure 存储中收到 404 错误。是的,blob 不存在,也没有参考。那么给定 CloudBlobClient,我如何将文件上传到 blob?
为了GetBlobReferenceFromServer
工作,blob 必须存在于 blob 存储中。当您知道 blob 存在于存储中并且想要找出 blob 的类型时,这在场景中很有用 -Block Blob
或Page Blob
.
如果您想通过从本地计算机上传文件来创建块 blob,您可以执行以下操作:
var blob = new CloudBlockBlob(new Uri(blobWithSas.AbsoluteUri), new StorageCredentials(blobWithSas.Sas));
using (var stream = new FileStream(fullFilePath, FileMode.Open))
{
blob.UploadFromStream(stream);
}
谈到共享访问签名功能,我不久前写了一篇关于此的博客文章:http://gauravmantri.com/2013/02/13/revisiting-windows-azure-shared-access-signature/
. 您可以将其称为史蒂夫博文的第 2 版:)。我展示了使用 REST API 和 Storage Client Library 2.0 上传具有共享访问签名的 blob 的示例。
博客文章中的一些代码示例:
使用存储客户端库:
/// <summary>
/// Uploads a blob in a blob container where SAS permission is defined on a blob container using storage client library.
/// </summary>
/// <param name="blobContainerSasUri"></param>
static void UploadBlobWithStorageClientLibrarySasPermissionOnBlobContainer(string blobContainerSasUri)
{
CloudBlobContainer blobContainer = new CloudBlobContainer(new Uri(blobContainerSasUri));
CloudBlockBlob blob = blobContainer.GetBlockBlobReference("sample.txt");
string sampleContent = "This is sample text.";
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(sampleContent)))
{
blob.UploadFromStream(ms);
}
}
使用 REST API:
/// <summary>
/// Uploads a blob in a blob container where SAS permission is defined on a blob container using REST API.
/// </summary>
/// <param name="blobContainerSasUri"></param>
static void UploadBlobWithRestAPISasPermissionOnBlobContainer(string blobContainerSasUri)
{
string blobName = "sample.txt";
string sampleContent = "This is sample text.";
int contentLength = Encoding.UTF8.GetByteCount(sampleContent);
string queryString = (new Uri(blobContainerSasUri)).Query;
string blobContainerUri = blobContainerSasUri.Split('?')[0];
string requestUri = string.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", blobContainerUri, blobName, queryString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "PUT";
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.ContentLength = contentLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
}
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
}
}
您可能还会发现这篇博文很有用:http://gauravmantri.com/2013/02/16/uploading-large-files-in-windows-azure-blob-storage-using-shared-access-signature-html-and-javascript/