Azure 本地存储帐户中的 WCF 上传 Blob
本文关键字:WCF 上传 Blob 存储 Azure | 更新日期: 2023-09-27 18:34:06
我目前正在使用 C# 和 Azure 存储开发 WCF Rest Web 服务,我需要在本地存储帐户中上传文件。目前,我已经能够在特定容器中上传特定文件,但是,我需要能够选择计算机中的任何文件并将其上传到我选择的容器上。
这里是服务中的上传代码:
[WebInvoke(Method = "GET", UriTemplate = "UploadBlob", ResponseFormat = WebMessageFormat.Json)]
public void UploadBlob()
{
// Connect to the storage account's blob endpoint
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("BlobConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Create the blob storage container
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists();
// Create the blob in the container
CloudBlockBlob blob = container.GetBlockBlobReference("nature");
using (var fileStream = System.IO.File.OpenRead(@"C:'Image'nature.jpg"))
{
blob.UploadFromStream(fileStream);
}
}
在这里,我将"自然.jpg"文件上传到"mycontainer"容器中。在我的 Web 表单中,单击按钮后,我使用以下代码调用该方法:
protected void Button1_Click(object sender, EventArgs e)
{
BlobService upload = new BlobService();
upload.UploadBlob();
}
这是我的按钮和文件上传输入的设计代码:
<asp:FileUpload ID="FileUpload" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload" />
当我单击此按钮时,自然.jpg被上传。我需要的是能够在我的计算机上选择一个文件并将其上传到我选择的容器中。
在按钮单击事件中,您可以访问在 FileUpload 控件中选择的图像:
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload.//Get you image and check if it is correct
BlobService upload = new BlobService();
upload.UploadBlob(<<give the image filestream to your upload server>>);
}
上传 Blob 应有一个流作为输入(文件图像)。
在按钮单击事件中,需要创建流,然后将其上载到 WCF 服务。
protected void Button1_Click(object sender, EventArgs e)
{
BlobService upload = new BlobService();
System.IO.FileStream streamToUpload = new System.IO.FileStream(FileUpload.PostedFile.FileName,
System.IO.FileMode.Open, System.IO.FileAccess.Read)
upload.UploadBlob(streamToUpload );
}
UploadBlob
服务方法的代码应如下所示:
[WebInvoke(Method = "GET", UriTemplate = "UploadBlob", ResponseFormat = WebMessageFormat.Json)]
public void UploadBlob(Stream fileStream)
{
// Connect to the storage account's blob endpoint
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("BlobConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Create the blob storage container
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists();
// Create the blob in the container
CloudBlockBlob blob = container.GetBlockBlobReference("nature");
blob.UploadFromStream(fileStream);
}