programing

Blob Storage Azure에 단일 파일 업로드

muds 2023. 5. 6. 16:45
반응형

Blob Storage Azure에 단일 파일 업로드

C#으로 파일을 업로드하려면 어떻게 해야 합니까? 대화창에서 파일을 업로드해야 합니다.

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 및 참조 정보는 여기를 참조하십시오.

그게 당신이 필요로 하는 것 같아요.

Windows Azure 이후.스토리지는 레거시입니다.마이크로소프트와 함께.애저, 저장고다음 코드를 사용하여 업로드할 수 있습니다.

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

다음 코드 조각은 파일 업로드를 수행하는 가장 간단한 형식입니다.업로드 파일 형식을 감지하고 컨테이너 확장자를 확인하기 위해 이 코드에 몇 줄을 더 추가했습니다.

참고:- 다음 NuGet 패키지를 먼저 추가해야 합니다.

  1. 마이크로소프트.AsNetCore.정적 파일

  2. 마이크로소프트.애저, 저장고블롭

  3. 마이크로소프트.내선 번호.배열

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

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 입력 필드를 통해 제공된 문자열 값을 사용하여 정의되며, 최종 사용자가 PickSingleFileAsync 작업에서 제공하는 UI를 통해 파일을 선택하면 StorageFile 개체로 표시되는 업로드할 파일이 반환됩니다.

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

그게 다야

여기 완전한 방법이 있습니다.

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

웹 API 컨트롤러를 완료하여 단일 또는 여러 파일을 업로드합니다. .NET Framework 4.8

NuGet 패키지, Azure를 설치합니다.저장소.블롭

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Configuration;
using System.Web;
using System.Web.Http;

namespace api.azure.Controllers
{
    public class FileController : ApiController
    {
        [HttpPost]
        [Route("api/BlobStorage/UploadFiles")]
        public IHttpActionResult UploadFiles()
        {
            string result = "";
            try
            {
                result = UploadFilesToBlob();
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }

            return Ok(result);
        }

        public string UploadFilesToBlob()
        {
            try
            {
                string storageConnectionString = ConfigurationManager.AppSettings["BlobStorageConnectionString"];
                CloudStorageAccount blobStorage = CloudStorageAccount.Parse(storageConnectionString);
                CloudBlobClient blobClient = blobStorage.CreateCloudBlobClient();
                if (HttpContext.Current.Request.Form["BlobContainerName"] != null)
                {
                    string blobContainerName = HttpContext.Current.Request.Form["BlobContainerName"].ToString();
                    CloudBlobContainer container = blobClient.GetContainerReference(blobContainerName);
                    container.CreateIfNotExists();

                    // Set public access level to the container.
                    container.SetPermissions(new BlobContainerPermissions()
                    {
                        PublicAccess = BlobContainerPublicAccessType.Container
                    });

                    string folderName = "";
                    if (HttpContext.Current.Request.Form["FolderNameToUploadFiles"] != null)
                    folderName = HttpContext.Current.Request.Form["FolderNameToUploadFiles"].ToString() + "/";

                    for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                    {
                        var httpPostedFile = HttpContext.Current.Request.Files[i];
                        if (httpPostedFile != null)
                        {
                            string blobName = folderName + httpPostedFile.FileName;
                            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
                            blob.UploadFromStream(httpPostedFile.InputStream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return "# of file(s) sent to upload: " + HttpContext.Current.Request.Files.Count.ToString();

        }
    }
}

언급URL : https://stackoverflow.com/questions/18597043/upload-a-single-file-to-blob-storage-azure

반응형