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
- Open Visual Studio 2022.
- Click on Create a new project.
- Select ASP.NET Core Web API and click Next.
- Name your project (e.g.,
FileUploadDownloadApi) and choose a location to save it. Click Next. - 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
In Solution Explorer, right-click on the Controllers folder, choose Add > Class, and name it
FileController.cs.Add the following code to
FileController.cs:
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:
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
- Run your application by pressing
F5or clicking theRunbutton. - Open Postman (or any API testing tool).
- Create a new POST request with the URL:
https://localhost:5001/api/file/upload. - Under the Body tab, select form-data and add a key named
file. Set the type to File, and choose a file to upload. - Click Send.
- You should receive a response containing the file path.
Download File
- After successfully uploading a file, note the file name.
- Create a new GET request with the URL:
, replacingtexthttps://localhost:5001/api/file/download/{fileName}{fileName}with the actual file name. - Click Send.
- 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.