File Upload Handling: API Endpoint and multipart/form-data

ASP.NET Core Web API with the multipart/form-data content type. you can create an endpoint that allows users to upload files to your server.

Create a new ASP.NET Core Web API project

Open Visual Studio and create a new ASP.NET Core Web Application project. Choose the API template.

Add a model for the uploaded file

Create a model class to represent the uploaded file. In this example, let's call it FileUploadModel.cs.

Author: Sardar Mudassar Ali Khan
public class FileUploadModel
{
    public IFormFile File { get; set; }
}

Configure the API Controller

Open the Controllers folder and create a new controller named FileUploadController.cs.

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

Author: Sardar Mudassar Ali Khan
[ApiController]
[Route("api/[controller]")]
public class FileUploadController : ControllerBase
{
    [HttpPost("upload")]
    public async Task<IActionResult> UploadFile([FromForm] FileUploadModel model)
    {
        if (model?.File == null || model.File.Length <= 0)
        {
            return BadRequest("No file was uploaded.");
        }

        // Define the folder where you want to save the uploaded files
        string uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "uploads");

        // Create the folder if it doesn't exist
        if (!Directory.Exists(uploadsFolder))
        {
            Directory.CreateDirectory(uploadsFolder);
        }

        // Generate a unique filename for the uploaded file
        string uniqueFileName = Path.GetRandomFileName();
        string filePath = Path.Combine(uploadsFolder, uniqueFileName);

        // Save the uploaded file to the specified path
        using (var fileStream = new FileStream(filePath, FileMode.Create))
        {
            await model.File.CopyToAsync(fileStream);
        }

        return Ok("File uploaded successfully.");
    }
}

Configure Startup.cs

Make sure that your Startup.cs file includes the necessary configurations for handling file uploads and configuring CORS if needed.

Author: Sardar Mudassar Ali Khan
public void ConfigureServices(IServiceCollection services)
{

    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Test the Endpoint

You can now test the file upload endpoint using a tool like Postman or any other API testing tool. Set the request method to POST and the URL to https://localhost/api/FileUpload/upload. In the body, choose the form-data option and add a key-value pair where the key is File (matching the property name in the FileUploadModel class) and the value is the file you want to upload.
Remember to replace the port with the actual port number your application is running on.

Please adapt the code to your specific requirements and perform additional error handling and validation as needed.

Conclusion

This example demonstrates how to handle file uploads via API endpoints using ASP.NET Core Web API with the multipart/form-data content type. By following the steps outlined above, you can create an endpoint that allows users to upload files to your server. Here's a brief summary of the key steps:

  1. Create a model class (FileUploadModel) to represent the uploaded file.
  2. Configure an API controller (FileUploadController) with a POST endpoint to handle file uploads.
  3. In the controller, validate the uploaded file and save it to a specified location on the server.
  4. Configure the Startup.cs file to add necessary services and middleware.
  5. Test the file upload endpoint using an API testing tool.

Remember that this example provides a basic foundation for handling file uploads. Depending on your application's requirements, you might need to enhance the error handling, security, and validation aspects. Additionally, ensure that you adapt the code to match your specific use case and integrate it into your project's architecture.


Similar Articles