将单个文件上载到Blob Storage Azure

问题描述 投票:28回答:3

如何使用C#上传文件?我需要从对话框窗口上传文件。

c# azure
3个回答
46
投票
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);
}

请参阅here关于所需的SDK和参考资料

我认为这就是你需要的


2
投票

我们可以使用BackgroundUploader类,然后我们需要提供StorageFile对象和一个Uri:Required Namespaces:

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;

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

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

然后:

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

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

就这样


1
投票

这是完整的方法。

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

其中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);
            }
© www.soinside.com 2019 - 2024. All rights reserved.