[筆記] Dotnet Core MVC C# 檔案上傳,使用Azure Blob 上傳、下載、刪除、複製

Dotnet Core MVC C# 檔案上傳 使用Azure Blob 上傳、下載、刪除、複製

檔案及目錄操作

安裝套件

使用NuGet 搜尋 Azure.Storage.Blobs

建立Service
using Azure.Storage.Blobs;

namespace BlobWeb.Service
{
    public class BlobService
    {
        private readonly string _connString = "連線字串";

        /// <summary>
        /// 上傳檔案到Azure Blob
        /// </summary>
        /// <param name="containerName">容器名稱</param>
        /// <param name="directoryPath">容器內的目錄 e.g. Images/User01</param>
        /// <param name="fileName">檔名 e.g. abc.png</param>
        /// <returns></returns>
        public bool UploadFile(IFormFile file, string containerName, string directoryPath, string fileName)
        {
            bool result = false;
            try
            {
                //建立連線並指定容器
                var containerClient = new BlobContainerClient(_connString, containerName);
                //若容器不存在則建立新容器
                containerClient.CreateIfNotExists();

                //取得連線物件的實體
                BlobClient blobClient = containerClient.GetBlobClient($"{directoryPath}/{fileName}");

                using (var stream = new MemoryStream())
                {
                    file.CopyTo(stream);

                    stream.Position = 0;

                    //上傳檔案
                    blobClient.Upload(stream, true);
                }

                result = true;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                result = false;
            }

            return result;
        }

        /// <summary>
        /// 從Azure Blob上刪除檔案
        /// </summary>
        /// <param name="containerName">容器名稱</param>
        /// <param name="directoryPath">容器內的目錄 e.g. Images/User01</param>
        /// <param name="fileName">檔名 e.g. abc.png</param>
        /// <returns></returns>
        public bool DeleteFile(string containerName, string directoryPath, string fileName)
        {
            bool result = false;
            try
            {
                //建立連線並指定容器
                var containerClient = new BlobContainerClient(_connString, containerName);

                //取得連線物件的實體
                BlobClient blobClient = containerClient.GetBlobClient($"{directoryPath}/{fileName}");

                //若檔案存在就刪除
                blobClient.DeleteIfExists();

                result = true;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                result = false;
            }

            return result;
        }

        /// <summary>
        /// 取得檔案並以MemoryStream型別回傳
        /// </summary>
        /// <param name="containerName">容器名稱</param>
        /// <param name="directoryPath">容器內的目錄 e.g. Images/User01</param>
        /// <param name="fileName">檔名 e.g. abc.png</param>
        /// <returns></returns>
        public MemoryStream GetMemoryStreamOfFile(string containerName, string directoryPath, string fileName)
        {
            //建立連線並指定容器
            var containerClient = new BlobContainerClient(_connString, containerName);

            //取得連線物件的實體
            BlobClient blobClient = containerClient.GetBlobClient($"{directoryPath}/{fileName}");

            var stream = new MemoryStream();

            blobClient.DownloadTo(stream);

            return stream;
        }

        /// <summary>
        /// 複製檔案
        /// </summary>
        /// <param name="sourceContainerName">來源容器名稱</param>
        /// <param name="sourceDirectoryPath">來源容器內的目錄 e.g. Images/User01</param>
        /// <param name="sourceFileName">來源檔名 e.g. abc.png</param>
        /// <param name="descContainerName">目的地容器名稱</param>
        /// <param name="descDirectoryPath">目的地容器內的目錄 e.g. NewImages/NewUser01</param>
        /// <param name="descFileName">目的地來源檔名 e.g. new_abc.png</param>
        /// <returns></returns>
        public bool CopyFile(string sourceContainerName, string sourceDirectoryPath, string sourceFileName, string descContainerName, string descDirectoryPath, string descFileName)
        {
            bool result;
            try
            {
                // Create a BlobServiceClient object which will be used to create a container client
                BlobServiceClient blobServiceClient = new BlobServiceClient(_connString);
                var sourceContainerClient = blobServiceClient.GetBlobContainerClient(sourceContainerName);
                //取得連線物件的實體(要複製的來源)
                BlobClient sourceBlobClient = sourceContainerClient.GetBlobClient($"{sourceDirectoryPath}/{sourceFileName}");
                if (sourceBlobClient.Exists())
                {
                    var descContainerClient = blobServiceClient.GetBlobContainerClient(descContainerName);
                    descContainerClient.CreateIfNotExists();

                    BlobClient descBlobClient = descContainerClient.GetBlobClient($"{descDirectoryPath}/{descFileName}");
                    descBlobClient.StartCopyFromUri(sourceBlobClient.Uri);
                }

                result = true;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                result = false;
            }

            return result;
        }

    }
}

上傳 Controller 部分
        public IActionResult Index()
        {
            return View();
        }
        

		/// <summary>單檔上傳</summary>
        [HttpPost]
        //把IIS上限改為200MB
        [RequestFormLimits(MultipartBodyLengthLimit = 209715200)]
        //把Kestrel Server上限改為200MB
        [RequestSizeLimit(209715200)]
        public IActionResult Index(IFormFile file)
        {
            if (file != null)
            {
                var blobService = new BlobService();

                blobService.UploadFile(file, "allentest", "MyFiles/User_Allen", file.FileName);
            }

            return View();
        }
        
        /// <summary>多檔上傳</summary>
        [HttpPost("MutiFile")]
        //把IIS上限改為200MB
        [RequestFormLimits(MultipartBodyLengthLimit = 209715200)]
        //把Kestrel Server上限改為200MB
        [RequestSizeLimit(209715200)]
        public IActionResult MutiFile(List<IFormFile> files)
        {
            if (files != null && files?.Any() == true)
            {
                foreach (var file in files)
                {
                    var blobService = new BlobService();

                    blobService.UploadFile(file, "allentest", "MyFiles/User_Allen", file.FileName);
                }
            }
            return View();
        }

 

上傳View部分
    <!--單檔上傳-->
    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
        <input type="file" name="file" />
        <br />
        <input type="submit" value="單檔送出" />
    </form>


	<!--多檔上傳-->
    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="MutiFile">
        <input type="file" name="files" multiple />
        <br />
        <input type="submit" value="多檔送出" />
    </form>
下載Controller 部分
        public IActionResult Download()
        {
            var blobService = new BlobService();

            var stream = blobService.GetMemoryStreamOfFile("allentest", "MyFiles/User_Allen", "abc.png");

            var fileBytes = stream.ToArray();

            return File(fileBytes, "image/png", "download.png");
        }
刪除Controller 部分
        public IActionResult Delete()
        {
            var blobService = new BlobService();

            blobService.DeleteFile("allentest", "MyFiles/User_Allen", "abc.png");

            return View();
        }
複製Controller 部分
        public IActionResult Copy()
        {
            var blobService = new BlobService();

            var stream = blobService.CopyFile("allentest", "MyFiles/User_Allen", "abc.png", "allentest", "MyFiles/User_Allen", "NewAbc.png");

            return View();
        }