WCF在Azure本地存储帐户中上载Blob

时间:2016-02-11 09:01:35

标签: c# wcf azure blob azure-storage-blobs

我目前正在使用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);
    }
}

这里我将“nature.jpg”文件上传到“mycontainer”容器中。 在我的网络表单中,我使用以下代码在单击按钮后调用该方法:

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" />

当我点击此按钮时,会上传nature.jpg。我需要的是能够在我的计算机上选择一个文件并将其上传到我选择的容器中。

2 个答案:

答案 0 :(得分:0)

在按钮单击事件中,您可以访问在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>>);
}

您的UploadBlob应该有一个流作为输入(文件图像)。

答案 1 :(得分:0)

在按钮单击事件中,您需要创建流,然后将其上载到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);

}