In modern web applications, file uploads are a common feature. Whether you’re building a document management system, user profile upload, or any other application, handling file uploads securely and efficiently is crucial. In this blog post, we’ll go through the steps to implement a file upload feature in a .NET Core web API using SQL Server to store file information. Additionally, we’ll cover how to handle the frontend using JavaScript.
1. Setting up the Project
a. Create a New .NET Core Web API Project
First, create a new .NET Core Web API project.
- Open Visual Studio and create a new project.
- Select ASP.NET Core Web API as the project template.
- Name the project
FileUploadDemo
. - Select .NET Core as the framework and ensure the API option is selected.
b. Install Required NuGet Packages
To interact with SQL Server, you will need the Microsoft.EntityFrameworkCore.SqlServer
package.
- Open NuGet Package Manager (right-click the project > Manage NuGet Packages).
- Search for and install:
Microsoft.EntityFrameworkCore.SqlServer
2. Setting Up the Database (SQL Server)
We’ll store the file metadata (name, type, size) and the actual file data as binary in the SQL Server.
a. Create the Files
Table
Here’s the SQL script to create the Files
table:
CREATE TABLE Files (
Id INT IDENTITY(1,1) PRIMARY KEY,
FileName NVARCHAR(255) NOT NULL,
ContentType NVARCHAR(100) NOT NULL,
Data VARBINARY(MAX) NOT NULL,
UploadDate DATETIME NOT NULL DEFAULT GETDATE()
);
Explanation:
FileName
: Stores the original name of the uploaded file.ContentType
: Stores the MIME type of the file (e.g., “application/pdf”).Data
: The actual file stored as binary data (VARBINARY(MAX)
).UploadDate
: The date when the file was uploaded.
3. Implementing the Backend in .NET Core
a. Define the Model
Create a FileModel
class to map to the Files
table:
public class FileModel
{
public int Id { get; set; }
public string FileName { get; set; }
public string ContentType { get; set; }
public byte[] Data { get; set; }
public DateTime UploadDate { get; set; }
}
b. Create a File Upload Controller
In the Controllers
folder, add a new controller named FileUploadController
:
[ApiController]
[Route("api/[controller]")]
public class FileUploadController : ControllerBase
{
private readonly FileContext _context;
public FileUploadController(FileContext context)
{
_context = context;
}
[HttpPost("upload")]
public async Task UploadFile([FromForm] IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest("No file uploaded.");
}
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
var fileModel = new FileModel
{
FileName = file.FileName,
ContentType = file.ContentType,
Data = stream.ToArray(),
UploadDate = DateTime.Now
};
_context.Files.Add(fileModel);
await _context.SaveChangesAsync();
}
return Ok(new { message = "File uploaded successfully." });
}
}
c. Setup Database Context
Add a FileContext
class in the Data
folder:
public class FileContext : DbContext
{
public FileContext(DbContextOptions options) : base(options) { }
public DbSet Files { get; set; }
}
d. Register the Database Context
In Startup.cs
(or Program.cs
in .NET 6/7), register the FileContext
:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<FileContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers();
}
Also, add your connection string in appsettings.json
:
"ConnectionStrings": {
"DefaultConnection": "Server=YourServerName;Database=YourDatabaseName;User Id=YourUsername;Password=YourPassword;"
}
4. Frontend: Uploading Files using JavaScript
a. HTML Form
Create a simple HTML form:
<form id="uploadForm">
<input type="file" id="fileInput" name="file" />
<button type="submit">Upload</button>
</form>
<p id="responseMessage"></p>
b. JavaScript to Handle File Upload
Add the following JavaScript to handle the form submission:
document.getElementById('uploadForm').addEventListener('submit', function (e) {
e.preventDefault(); // Prevent the form from submitting normally
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
if (!file) {
alert('Please select a file.');
return;
}
var formData = new FormData();
formData.append('file', file);
fetch('/api/FileUpload/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
document.getElementById('responseMessage').innerText = data.message;
})
.catch(error => {
console.error('Error:', error);
alert('File upload failed!');
});
});
5. Testing the Upload
Once you’ve set up the backend and frontend:
- Run the application (
Ctrl + F5
). - Open the browser and select the HTML page with the file input form.
- Select a file and click “Upload”.
- You should see a success message, and the file metadata should be stored in your database.
6. Downloading Files (Optional)
If you want to add a feature to download the uploaded files:
- Add a new endpoint in your
FileUploadController
: - In your frontend, you can create a button that allows the user to download the file.
[HttpGet("download/{id}")]
public async Task DownloadFile(int id)
{
var file = await _context.Files.FindAsync(id);
if (file == null)
{
return NotFound();
}
return File(file.Data, file.ContentType, file.FileName);
}
Conclusion
In this blog post, we walked through creating a full-featured file upload system using .NET Core, SQL Server, and JavaScript. This step-by-step guide covered setting up the project, handling file uploads on the server side, storing the file data in the database, and interacting with the API using JavaScript. By following this guide, you can implement file uploads in your .NET Core applications!