using blazor and dapper and MSSQLserver
want to upload a PDF file into the database table and then save a record . and again preview the file.
using blazor and dapper and MSSQLserver
want to upload a PDF file into the database table and then save a record . and again preview the file.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sarthak VarshneyRank #46 · 32K reputationPosted May 24, 2024, 9:15 PM EDT
To upload, save, and preview a PDF file using Blazor, Dapper, and SQL Server, you'll need to follow several steps. Here is a detailed guide to help you achieve this:
CREATE TABLE PdfFiles ( Id INT PRIMARY KEY IDENTITY, FileName NVARCHAR(255), FileData VARBINARY(MAX) );dotnet new blazorserver -n PdfUploadDemo cd PdfUploadDemousing Dapper; using System.Data.SqlClient; using System.Threading.Tasks; public class PdfService { private readonly string _connectionString; public PdfService(string connectionString) { _connectionString = connectionString; } public async Task UploadPdfAsync(string fileName, byte[] fileData) { using (var connection = new SqlConnection(_connectionString)) { var query = "INSERT INTO PdfFiles (FileName, FileData) VALUES (@FileName, @FileData); SELECT CAST(SCOPE_IDENTITY() as int)"; var parameters = new { FileName = fileName, FileData = fileData }; var id = await connection.QuerySingleAsync(query, parameters); return id; } } public async Task GetPdfAsync(int id) { using (var connection = new SqlConnection(_connectionString)) { var query = "SELECT FileName, FileData FROM PdfFiles WHERE Id = @Id"; var result = await connection.QuerySingleOrDefaultAsync(query, new { Id = id }); return result; } } }PdfServicein theStartup.csorProgram.csfile.builder.Services.AddSingleton(new PdfService("YourConnectionStringHere"));Upload.razor:
Preview.razor:
NavMenu.razorto access the upload and preview pages.Run Your Application: Run your Blazor application and navigate to the upload page to upload a PDF file, then navigate to the preview page to view the uploaded PDF.
This setup covers the basic functionality for uploading and previewing PDF files using Blazor, Dapper, and SQL Server. You can expand this further by adding more features like file validation, error handling, and user authentication.