ASP.NET Web API | File Upload and Download
--
ASP.NET Web API is a framework for building HTTP services that can be accessed by various clients, including web browsers, mobile devices, and desktop applications. It is built on top of the ASP.NET framework and uses the HTTP protocol to transmit data in a lightweight and efficient manner.
Web APIs are typically used to expose data and functionality from a web application to other systems or clients. For example, an e-commerce website may use a Web API to expose product information and inventory levels to mobile apps and other third-party systems.
Uploading and downloading files is a common requirement for web applications. In an ASP.NET Web API, file upload and download can be implemented using the HttpClient
class to send and receive files.
To upload a file in an ASP.NET Web API, we have created a service that handles upload and download files.
Here are the full project steps,
Service for Manage Files
public interface IManageImage
{
Task<string> UploadFile(IFormFile _IFormFile);
Task<(byte[], string, string)> DownloadFile(string FileName);
}
Service Implementation
public class ManageImage : IManageImage
{
public async Task<string> UploadFile(IFormFile _IFormFile)
{
string FileName = "";
try
{
FileInfo _FileInfo = new FileInfo(_IFormFile.FileName);
FileName = _IFormFile.FileName + "_" + DateTime.Now.Ticks.ToString() + _FileInfo.Extension;
var _GetFilePath = Common.GetFilePath(FileName);
using (var _FileStream = new FileStream(_GetFilePath, FileMode.Create))
{
await _IFormFile.CopyToAsync(_FileStream);
}
return FileName;
}
catch (Exception ex)
{
throw ex;
}
}
public async Task<(byte[], string, string)> DownloadFile(string FileName)
{
try
{
var _GetFilePath = Common.GetFilePath(FileName);
var provider = new FileExtensionContentTypeProvider();
if (!provider.TryGetContentType(_GetFilePath, out var _ContentType))
{
_ContentType = "application/octet-stream";
}
var _ReadAllBytesAsync = await File.ReadAllBytesAsync(_GetFilePath);
return (_ReadAllBytesAsync, _ContentType, Path.GetFileName(_GetFilePath));
}
catch (Exception ex)
{
throw ex;
}
}
}
API to Handle Files
[ApiController]
public class FileManagerController : ControllerBase
{
private readonly IManageImage _iManageImage;
public FileManagerController(IManageImage iManageImage)
{
_iManageImage = iManageImage;
}
[HttpPost]
[Route("uploadfile")]
public async Task<IActionResult> UploadFile(IFormFile _IFormFile)
{
var result = await _iManageImage.UploadFile(_IFormFile);
return Ok(result);
}
[HttpGet]
[Route("downloadfile")]
public async Task<IActionResult> DownloadFile(string FileName)
{
var result = await _iManageImage.DownloadFile(FileName);
return File(result.Item1, result.Item2, result.Item2);
}
}
Adding Custom Services in Program.cs
using API.FileProcessing.Service;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddTransient<IManageImage, ManageImage>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Get File Directory
public static string GetCurrentDirectory()
{
var result = Directory.GetCurrentDirectory();
return result;
}
public static string GetStaticContentDirectory()
{
var result = Path.Combine(Directory.GetCurrentDirectory(), "Uploads\\StaticContent\\");
if (!Directory.Exists(result))
{
Directory.CreateDirectory(result);
}
return result;
}
public static string GetFilePath(string FileName)
{
var _GetStaticContentDirectory = GetStaticContentDirectory();
var result = Path.Combine(_GetStaticContentDirectory, FileName);
return result;
}
Project Output
In summary, file upload and download are common features in ASP.NET Web API applications. To implement file upload and download, we need to use IManageImage interface. For file download, we can use the IActionResult
class to send the file content back to the client. It's important to properly validate and sanitize the file name and content to prevent security vulnerabilities. Additionally, we can use third-party libraries like AutoMapper to simplify the mapping of data models to view models, and Swagger to generate documentation for our Web API.
👋 My Portfolio
🚀 My Youtube Channel
💻 https://github.com/shahedbd/API.FileProcessing