41

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

4

5 回答 5

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

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

我认为这是你需要的

于 2013-09-03T17:17:13.073 回答
5

Since WindowsAzure.Storage is legacy. With Microsoft.Azure.Storage.* we can use the following code to upload

  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();
    }
于 2020-12-22T12:15:27.357 回答
3

以下代码片段是执行文件上传的最简单形式。我在此代码中添加了几行,以检测上传文件类型并检查容器是否存在。

注意:- 您需要先添加以下 NuGet 包。

  1. Microsoft.AspNetCore.StaticFiles

  2. Microsoft.Azure.Storage.Blob

  3. Microsoft.Extensions.Configuration

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        string connstring = "DefaultEndpointsProtocol=https;AccountName=storageaccountnewne9d7b;AccountKey=3sUU8J5pQQ+6YYIi+b5jo+BiSb5XPt027Rve6N5QP9iPEhMXZAbzUfsuW7QDWi1gSPecsPFpC6AzmA9jwPYs6g==;EndpointSuffix=core.windows.net";
        string containername = "newturorial";
        string finlename = "TestUpload.docx";
        var fileBytes = System.IO.File.ReadAllBytes(@"C:\Users\Namal Wijekoon\Desktop\HardningSprint2LoadTest\" + finlename);
    
        var cloudstorageAccount = CloudStorageAccount.Parse(connstring);
        var cloudblobClient = cloudstorageAccount.CreateCloudBlobClient();
        var containerObject = cloudblobClient.GetContainerReference(containername);
    
        //check the container existance
        if (containerObject.CreateIfNotExistsAsync().Result)
        {
            containerObject.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
        }
        var fileobject = containerObject.GetBlockBlobReference(finlename);
    
        //check the file type
        string file_type;
        var provider = new FileExtensionContentTypeProvider();
        if(!provider.TryGetContentType(finlename, out file_type))
        {
            file_type = "application/octet-stream";
        }
    
        fileobject.Properties.ContentType = file_type;
        fileobject.UploadFromByteArrayAsync(fileBytes, 0 , fileBytes.Length);
    
        string fileuploadURI = fileobject.Uri.AbsoluteUri;
        Console.WriteLine("File has be uploaded successfully.");
        Console.WriteLine("The URL of the Uploaded file is : - \n" + fileuploadURI);
    }
    
于 2021-01-03T17:32:45.060 回答
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;

过程如下: 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);

就这样

于 2013-09-03T16:55:13.813 回答
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);
            }
于 2017-12-29T21:14:17.547 回答