Friday, January 22, 2021

Uploading files with ASP.NET Core

 To upload file you can use Model type  IFormFile, which is found in the Microsoft.AspNet.Http namespace.

On View 

<form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
    <input type="file" name="files" multiple/>
    <input type="submit" value="Upload" />
</form>

On Controller

public class HomeController : Controller
{
    private IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(ICollection<IFormFile> files)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "uploads");
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
            }
        }
        return View();
    }
}

Notes that we receive files using ICollection<IFormFile>
IFormFile objects share some properties, methods like 
Length
- FileName
- Name : returns the value of the name attribute on the upload control.
- CopyToAsync method to save file to HD


To Upload multi-Files with other form info, use Model like this 
public class FileDescriptionShort
{
        public int Id { get; set; }
        public string Description { get; set; }
        public string Name { get; set; }
        public ICollection<IFormFile> File { get; set; }
}

public async Task<IActionResult> Index(FileDescriptionShort fileDescriptionShort)
{ }


To Upload One File use define it in Model like this
        [Required]
        [FileExtensions(Extensions = "jpg,jpeg")]
        public IFormFile File { get; set; }
For Multi-Files use 
        [Required]
        public ICollection<IFormFile> File { get; set; }

To download file from FileTable based on file ID

        PM> Install-Package Microsoft.AspNetCore.StaticFiles

        public string Get_contentType(string fileName)
        {
            var provider = new FileExtensionContentTypeProvider();
            string contentType;
            if (!provider.TryGetContentType(fileName, out contentType))
            {
                contentType = "application/octet-stream";
            }
            return contentType;
        }

        [HttpGet]
        public FileStreamResult Download(int id)
        {
            var path = "c:\\path\\a.pdf";
            var stream = new FileStream(path, FileMode.Open);
            return  File(stream, Get_contentType(path) );
        }

How to upload file to amazon s3 through web api

        [HttpPost]
        public async Task<string> PostAsync([FromBody] string FileName, IFormFile File2Upload)
        {
            if (File2Upload != null)
            {
                using (var client = new AmazonS3Client(AWSkey, AwsSecret, RegionEndpoint.USEast2))
                {
                    using (var newMemoryStream = new MemoryStream())
                    {
                        File2Upload.CopyTo(newMemoryStream);

                        var uploadRequest = new TransferUtilityUploadRequest
                        {
                            InputStream = newMemoryStream,
                            Key = FileName, //fileUpload.ProfileImage.FileName.ToString(),
                            BucketName = S3folderName,
                            CannedACL = S3CannedACL.PublicRead
                        };

                        var fileTransferUtility = new TransferUtility(client);
                        await fileTransferUtility.UploadAsync(uploadRequest);
                    }
                }
                return "https://S3folderName.s3.us-east-2.amazonaws.com/" + FileName;
} return ""; }

No comments: