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 Amazon.S3; using Amazon.S3.Transfer; namespace ArabAuthorsIndex.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; var newMemoryStream = new MemoryStream(); File2Upload.CopyTo(newMemoryStream); var s3ClientConfig = new AmazonS3Config { ServiceURL = "https://sgp1.digitaloceanspaces.com" }; IAmazonS3 s3Client = new AmazonS3Client(AccessKey, SecretKey, s3ClientConfig); try { var fileTransferUtility = new TransferUtility(s3Client); var fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = "ddl-temp" , InputStream = newMemoryStream, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB Key = fileName, CannedACL = S3CannedACL.PublicRead }; fileTransferUtility.Upload(fileTransferUtilityRequest); return $"https://ddl-temp.sgp1.digitaloceanspaces.com/{fileName}"; } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); if (e.Message.Contains("disposed")) return ""; } return ""; } [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(); fileName = string.IsNullOrEmpty(Name) ? $"{DateTime.Now.Ticks}-{fileName.Replace(" ", "-")}" : Name; // Download the file from the URL and upload it to S3 using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync(fileURL)) { if (!response.IsSuccessStatusCode) { return URL; // Handle download errors } using (var newMemoryStream = await response.Content.ReadAsStreamAsync()) { var s3ClientConfig = new AmazonS3Config { ServiceURL = "https://sgp1.digitaloceanspaces.com" }; IAmazonS3 s3Client = new AmazonS3Client(AccessKey, SecretKey, s3ClientConfig); try { var fileTransferUtility = new TransferUtility(s3Client); var fileTransferUtilityRequest = new TransferUtilityUploadRequest { BucketName = "ddl-temp", InputStream = newMemoryStream, StorageClass = S3StorageClass.StandardInfrequentAccess, PartSize = 6291456, // 6 MB Key = fileName, CannedACL = S3CannedACL.PublicRead }; fileTransferUtility.Upload(fileTransferUtilityRequest); return $"https://ddl-temp.sgp1.digitaloceanspaces.com/{fileName}"; } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); if (e.Message.Contains("disposed")) return ""; } } } } return $"https://ddl-temp.sgp1.digitaloceanspaces.com/{fileName}"; } catch (Exception ex) { return ""; } } } }
//Notes
Install the AWS SDK:
- Make sure you have the AWS SDK for .NET (
AWSSDK.S3
) installed in your project. You can use NuGet Package Manager to install it.