将单个文件上载到Blob Storage Azure

use*_*304 31 c# azure

如何使用C#上传文件?我需要从dialogWindow上传文件.

Lui*_*uel 49

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;    

// Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("StorageKey");

// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");

// Retrieve reference to a blob named "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(@"path\myfile"))
{
    blockBlob.UploadFromStream(fileStream);
}
Run Code Online (Sandbox Code Playgroud)

在这里看到所需的SDK和参考资料

我认为这就是你需要的

  • 这些库现在都是遗留的。不要使用此代码 (5认同)
  • 对于像我这样的新手:“ myblob”只是目标文件名。 (2认同)

raj*_*jat 11

由于 WindowsAzure.Storage 是遗留的。通过Microsoft.Azure.Storage.*我们可以使用下面的代码来上传

  static async Task CreateBlob()
    {
        
        BlobServiceClient blobServiceClient = new BlobServiceClient(storageconnstring);
        
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
        
        BlobClient blobClient = containerClient.GetBlobClient(filename);

        
        using FileStream uploadFileStream = File.OpenRead(filepath);
        
        await blobClient.UploadAsync(uploadFileStream, true);
        uploadFileStream.Close();
    }
Run Code Online (Sandbox Code Playgroud)


Ham*_*med 2

我们可以使用BackgroundUploader类,然后我们需要提供StorageFile对象和一个Uri:必需的命名空间:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage.Pickers;
using Windows.Storage;
Run Code Online (Sandbox Code Playgroud)

过程如下:Uri 是使用通过 UI 输入字段提供的字符串值来定义的,当最终用户通过 UI 输入字段提供的 UI 选择文件时,将返回由 StorageFile 对象表示的所需上传文件。 PickSingleFileAsync 操作

Uri uri = new Uri(serverAddressField.Text.Trim());
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();
Run Code Online (Sandbox Code Playgroud)

进而:

BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);

// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);
Run Code Online (Sandbox Code Playgroud)

就这样