Saturday, June 22, 2024

Step-by-Step Guide for File Upload and Download in .NET 8 using Visual Studio 2022

 

In this guide, we will create a simple .NET application that allows users to upload and download files. We will use Visual Studio 2022 to create our project and implement the necessary features. By the end of this tutorial, you will have a working API that handles file uploads and downloads.

Prerequisites:


  • .NET 8 SDK installed
  • Visual Studio 2022 installed

1. Create a New .NET 8 Project

    
  1. Open Visual Studio 2022.
  2. Click on Create a new project.
  3. Select ASP.NET Core Web API and click Next.
  4. Name your project (e.g., FileUploadDownloadApi) and choose a location to save it. Click Next.
  5. Select .NET 8 as the Framework and keep the default settings. Click Create.

2. Set Up the Project Structure


Our project structure will look like this:


FileUploadDownloadApi
│
├── Controllers
│   └── FileController.cs
├── Properties
│   └── launchSettings.json
├── appsettings.json
├── Program.cs
└── <other files>

3. Create FileController

  1. In Solution Explorer, right-click on the Controllers folder, choose Add > Class, and name it FileController.cs.

  2. Add the following code to FileController.cs:

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

namespace FileUploadDownloadApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        private readonly string _storagePath = Path.Combine(Directory.GetCurrentDirectory(), "Uploads");

        public FileController()
        {
            if (!Directory.Exists(_storagePath))
            {
                Directory.CreateDirectory(_storagePath);
            }
        }

        [HttpPost("upload")]
        public async Task<IActionResult> UploadFile([FromForm] IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("No file uploaded.");
            }

            var filePath = Path.Combine(_storagePath, file.FileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Ok(new { FilePath = filePath });
        }

        [HttpGet("download/{fileName}")]
        public IActionResult DownloadFile(string fileName)
        {
            var filePath = Path.Combine(_storagePath, fileName);

            if (!System.IO.File.Exists(filePath))
            {
                return NotFound("File not found.");
            }

            var bytes = System.IO.File.ReadAllBytes(filePath);
            return File(bytes, "application/octet-stream", fileName);
        }
    }
}

4. Update Program.cs

Ensure that your Program.cs file includes the necessary middleware and service configurations:

csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

app.Run();

5. Testing the API

Upload File

  1. Run your application by pressing F5 or clicking the Run button.
  2. Open Postman (or any API testing tool).
  3. Create a new POST request with the URL: https://localhost:5001/api/file/upload.
  4. Under the Body tab, select form-data and add a key named file. Set the type to File, and choose a file to upload.
  5. Click Send.
  6. You should receive a response containing the file path.


Download File

  1. After successfully uploading a file, note the file name.
  2. Create a new GET request with the URL:
    text
    https://localhost:5001/api/file/download/{fileName}
    , replacing {fileName} with the actual file name.
  3. Click Send.
  4. The file should be downloaded to your machine.

Replace the URL with an actual screenshot URL

6. Conclusion

In this tutorial, we created a .NET 8 Web API using Visual Studio 2022 to handle file uploads and downloads.