C# 将单个文件上传到 Blob 存储 Azure

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18597043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:41:38  来源:igfitidea点击:

Upload a Single File to Blob Storage Azure

c#azure

提问by user2476304

How can I to Upload a file with C# ? I need to upload a file from a dialogWindow.

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

回答by Hamed

we can use BackgroundUploaderclass ,Then we need to provide StorageFileobject and a Uri: Required Namespaces:

我们可以使用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;

The process is Like This : Uri is defined using a string value provided via a UI input field, and the desired file for upload, represented by a StorageFile object, is returned when the end-user has selected a file through the UI provided by the PickSingleFileAsync operation

过程是这样的:Uri 是使用通过 UI 输入字段提供的字符串值定义的,当最终用户通过PickSingleFileAsync 操作

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

and Then:

进而:

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

// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);

Thats All

就这样

回答by Luis Miguel

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);
}

see hereabout needed SDK and references

请参阅此处了解所需的 SDK 和参考资料

i think it's what you need

我认为这是你需要的

回答by Debendra Dash

Here is the complete method.

这是完整的方法。

 [HttpPost]
        public ActionResult Index(Doctor doct, HttpPostedFileBase photo)
        {

            try
            {
                if (photo != null && photo.ContentLength > 0)
                {
                    // extract only the fielname
                    var fileName = Path.GetFileName(photo.FileName);
                    doct.Image = fileName.ToString();

                    CloudStorageAccount cloudStorageAccount = DoctorController.GetConnectionString();
                    CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
                    CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");


                    string imageName = Guid.NewGuid().ToString() + "-" +Path.GetExtension(photo.FileName); 

                    CloudBlockBlob BlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);

                    BlockBlob.Properties.ContentType = photo.ContentType;
                    BlockBlob.UploadFromStreamAsync(photo.InputStream);
                    string imageFullPath = BlockBlob.Uri.ToString();

                    var memoryStream = new MemoryStream();


                    photo.InputStream.CopyTo(memoryStream);
                    memoryStream.ToArray();



                    memoryStream.Seek(0, SeekOrigin.Begin);
                    using (var fs = photo.InputStream)
                    {
                        BlockBlob.UploadFromStreamAsync(memoryStream);
                    }

                }
            }
            catch (Exception ex)
            {

            }


            return View();
        }

where the getconnectionstring method is this.

getconnectionstring 方法在哪里。

 static string accountname = ConfigurationManager.AppSettings["accountName"];
      static  string key = ConfigurationManager.AppSettings["key"];


            public static CloudStorageAccount GetConnectionString()
            {

                string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountname, key);
                return CloudStorageAccount.Parse(connectionString);
            }