Angular File Uploader - How to upload images using ASP.NET Core API Controller

This example contains an Angular client-side application with DevExtreme File Uploader. The control uploads image files to the ASP.NET Core API Controller and returns the uploaded images as the base64 strings to the client.

Files to look at:

Implementation:

  1. Configure your Angular application as described in the Add DevExtreme to an Angular CLI Application article. Register the DevExtreme FileUploader module in the app.module.ts file.
  2. Add the FileUploader component to one of your Angular components files. Specify its name option and set the uploadUrl option so that it points to your ASP.NET Core API Controller.
<dx-file-uploader name='myFile' uploadUrl="/FileUpload" [multiple]="true"
  accept="*"  uploadMode="instantly">
</dx-file-uploader>
  1. Create an API Controller in your ASP.NET Core application and a method to save an uploaded file. Note that the method's parameter name should be equal to your FileUploader's name.
 public async Task<IActionResult> AsyncUpload(IFormFile myFile) {
            string targetLocation = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
            try {
                if (!Directory.Exists(targetLocation))
                    Directory.CreateDirectory(targetLocation);
                using (var fileStream = System.IO.File.Create(Path.Combine(targetLocation, myFile.FileName))) {
                    myFile.CopyTo(fileStream);
                }
            } catch {
                Response.StatusCode = 400;
            }
            ...
 }
  1. (Optional) If you need to display an uploaded image file as a base64 string, convert it to a byte array in your Controller.Then get the base64 string from this array with Convert.ToBase64String and return the result from your method.
  2. (Optional) To display the image after uploading, handle the onUploaded event (see Angular - Component Configuration Syntax - Event Handling) and append the "IMG" tag in this event handler.
export class HomeComponent {
    onUploaded(e) {
        var image = document.createElement("IMG");
        image.setAttribute("src", "data:image/jpg;base64," + e.request.responseText);
        var container = document.getElementById("imagesContainer");
        container.appendChild(image);
    }
}