Wednesday, March 22, 2023

Upload Files to Azure using c# API

 

When user choose any file from local HD [in the second textbox], or put any external URL in the first textbox, a callback event will run and upload this file to Azure blob and put the short link in the first textbox to save to database as varchar[200]

OnChange in Javascript call C# API method that can accept File or URL








<form asp-action="Create">
		<div class="form-group position-relative">
			<label asp-for="Image" class="control-label"></label>
			<input asp-for="Image" class="form-control" id="ximage-form" />
			<span asp-validation-for="Image" class="text-danger"></span>
			<div class="input-group mb-3 custom-file-with-url">
				<div class="custom-file">
					<input type="file" class="custom-file-input" id="ximage-file" aria-describedby="inputGroupFileAddon01" accept="image/*" >
					<label class="custom-file-label" for="ximage-file"></label>
				</div>
			</div>
			<div class="row">
				<img id="xloading-img" class="d-none mx-auto" src="~/assets/images/loading.gif" alt="" />
			</div>
		</div>
		<div class="form-group">
			<input id="submit-btn" type="submit" value="Create" class="btn btn-primary" />
		</div>
</form>


<script>
	function isImage(url) {
	  return /^https?:\/\/.+\.(jpg|jpeg|png|webp|avif|gif|svg)$/.test(url);
	}

    $(document).ready(function () {
        $("#ximage-form").change(function () {
				var file = $("#ximage-form").val();
                console.log(file);

                if (!(isImage(file))) {
                    alert("It is not a image. Please choose a image format file to upload.");
                    return;
                }

                const fd = new FormData();

                fd.append("URL", file);
                $("#submit-btn").addClass("d-none");
                $("#xloading-img").removeClass("d-none");
                $.ajax({
                    url: "/FileUpload/Upload",
                    enctype: 'multipart/form-data',
                    method: "PUT",
                    processData: false,
                    contentType: false,
                    cache: false,
                    data: fd,
                    success: function (data) {
                        $("#ximage-form").val(data);
                        $("#submit-btn").removeClass("d-none");
                        $("#xloading-img").addClass("d-none");
                    }
                });

            
        });
    });
</script>

<script>
    $(document).ready(function () {
        $("#ximage-file").change(function () {
            const files = [...document.querySelector('#ximage-file').files];
            files.forEach(file => {
                console.log(file);

                if (!file.type.match("image/")) {
                    alert(file.name + " is not a image. Please choose a image format file to upload.");
                    console.log(file.type);
                    return;
                }

                const fd = new FormData();

                fd.append("File2Upload", file);
                $("#submit-btn").addClass("d-none");
                $("#xloading-img").removeClass("d-none");
                $.ajax({
                    url: "/FileUpload/Upload",
                    enctype: 'multipart/form-data',
                    method: "POST",
                    processData: false,
                    contentType: false,
                    cache: false,
                    data: fd,
                    success: function (data) {
                        $("#ximage-form").val(data);
                        $("#submit-btn").removeClass("d-none");
                        $("#xloading-img").addClass("d-none");
                    }
                });

            });
        });
    });
</script>




using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Azure.Storage.Blobs;
namespace MyProject.Controllers
{
    public class FileUploadController : Controller
    {
        [HttpPost]
        public async Task<string> Upload([FromForm] IFormFile File2Upload, [FromForm] string Name)
        {
            if (File2Upload == null) return "";

            string fileName = string.IsNullOrEmpty(Name) ? $"{DateTime.Now.Ticks}-{File2Upload.FileName.Replace(" ", "-")}" : Name;

            //Console.WriteLine("Starting...");
            var blobStorageConnectionString = "DefaultEndpointsProtocol=https;AccountName=XYZ;AccountKey=****;EndpointSuffix=core.windows.net";
            var blobStorageContainerName = "ABCD";
            var container = new BlobContainerClient(blobStorageConnectionString, blobStorageContainerName);
            var newMemoryStream = new MemoryStream();
            File2Upload.CopyTo(newMemoryStream);
            var blob = container.GetBlobClient(fileName);
            newMemoryStream.Position = 0;

            await blob.UploadAsync(newMemoryStream);
            //Console.WriteLine("Upload completed.");
            return $"https://XYZ.blob.core.windows.net/ABCD/{fileName}";
        }



        [HttpPut]
        public async Task<string> Upload( string URL,string Name)
        {
            try
            {
                if (URL == null) return "";
                Uri fileURL = new Uri(URL);
                var FileName = fileURL.Segments.Last();


                string fileName = string.IsNullOrEmpty(Name) ? $"{DateTime.Now.Ticks}-{FileName.Replace(" ", "-")}" : Name;

                //Console.WriteLine("Starting...");
                var blobStorageConnectionString = "DefaultEndpointsProtocol=https;AccountName=XYZ;AccountKey=****;EndpointSuffix=core.windows.net";
                var blobStorageContainerName = "ABCD";
                var container = new BlobContainerClient(blobStorageConnectionString, blobStorageContainerName);

                var blob = container.GetBlobClient(fileName);
                System.Threading.CancellationTokenSource cToken = new System.Threading.CancellationTokenSource();
                cToken.CancelAfter(30000);
                var status = await blob.StartCopyFromUriAsync(fileURL, null, cToken.Token);
                await status.WaitForCompletionAsync();

                //Console.WriteLine("Upload completed.");
                return $"https://XYZ.blob.core.windows.net/ABCD/{fileName}";
            }
            catch (Exception ex) { return ""; }
        }
    }
}