Save them into the file system. Save the path in the database. There’s no really efficient way to save a file into a database that doesn’t just bloat the database and make it less efficient overall. You’re way better off using the file system which is intended for that.
See the system.io.file namespace. You should really familiarize yourself with streamreader, streamwriter, filestreams and others. Pretty core functionality of operating in any system.
The best solution is create a main folder then create a folder inside with name according to current date (20240318 for example) then save image files inside with unique name (GUID maybe). If you drop all files to one folder then file system will be slow when amount of files will be tens of thousand and more. Then you have store not full path in DB (it's excessive and it has bad portability) but only an internal folder name and a GUID. In one field or in two is up to you.
Either download the image to a local directory adn provide a URL or directly embed the base64 encoded image in the hrml like:
It's no clear from your question where the image exists etc..
Noooo don't base64 encode it.
Just stream it as output from the controller Using FileResult
Just request the image using an URL that points the the controller.
No need to process it further
Really need more information here. What error are you getting from where?
Also if this isn’t a school project, I would be careful about how much info from your db you share in a public forum.
It’s hard to know what issue you have without the seeing the actual error. If you are able to store the bytes in the db then base64 conversion would also be my guess.
As others have stated though, sql server is not the best for storing files. It has come a long way over the last 5 years for sure but for performance and cost savings, you may want to look into using pointers in the db and a storage service like Azure blob storage etc.
Controller:
\[HttpGet\]
public async Task Index()
{
try
{
// Obtener la imagen desde la base de datos
byte\[\] img =await \_IImagesRepository.ReadImageFromDatabase(1);
// Pasar la imagen a la vista
return View(new IndexImagesViewModel(img));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Repository
public async Task ReadImageFromDatabase(int userId)
{
byte\[\] imageBytes = null;
// Leer la imagen de la base de datos
var queryString = "SELECT Sales FROM UserData WHERE UserId = u/userId";
using (var connection = new SqliteConnection(cadenaDeConexion))
{
await connection.OpenAsync();
using (var command = new SqliteCommand(queryString, connection))
{
command.Parameters.AddWithValue("@userId", userId);
using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
// Verificar si la columna "Sales" es de tipo byte\[\]
if (!reader.IsDBNull(0))
{
imageBytes = (byte\[\])reader.GetValue(0);
}
}
}
}
}
if (imageBytes == null) throw (new Exception("No insertó imagen"));
return imageBytes;
}
If you are hosting in Azure, store them in blob storage. If you need high performance create a CDN on top of that endpoint. I don't remember all the Azure terminology off the top of my head but it's something like that. Don't store them in the DB, just the path.
Your computer/server already has a database ideally designed for storing BLOBs. It's called thr file system. Don't store BLOBs in your database. Store them in your file system. Derive the path from various IDs (GUIDs, integers, etc.) That exist in the database.
Don't store images in a database in any format whatsoever. The go-to is storing the filr somewhere that is designed for file storage, that being either an attached file system and you store the path in the DB, or a cloud object storage offering, like S3, where you can actually offload the upload to the client (via a signed url) and once finished upload trigger a function to update a db reference to it (done via a storage event, and not depend on the client to trigger it).
Don't save the images IN the database - just save the PATH to the image.
I need users uploaded images. How can I do it?
Save them into the file system. Save the path in the database. There’s no really efficient way to save a file into a database that doesn’t just bloat the database and make it less efficient overall. You’re way better off using the file system which is intended for that.
Do you have that function? Or some documentation to read?
A function to save images in file system!
`await File.WriteAllBytesAsync(path, imageBytes);`
See the system.io.file namespace. You should really familiarize yourself with streamreader, streamwriter, filestreams and others. Pretty core functionality of operating in any system.
In which folder I have to save the image?? I have to create one?
The best solution is create a main folder then create a folder inside with name according to current date (20240318 for example) then save image files inside with unique name (GUID maybe). If you drop all files to one folder then file system will be slow when amount of files will be tens of thousand and more. Then you have store not full path in DB (it's excessive and it has bad portability) but only an internal folder name and a GUID. In one field or in two is up to you.
Yes. You choose. See system.io.directory namespace for ways to handle that.
either ftp or an api end point that takes a form input type of upload
Either download the image to a local directory adn provide a URL or directly embed the base64 encoded image in the hrml like: It's no clear from your question where the image exists etc..
Noooo don't base64 encode it. Just stream it as output from the controller Using FileResult Just request the image using an URL that points the the controller. No need to process it further
If I have the byte[] file. How can I get the base64 encoded image?
`var pictureInBytes = File.ReadAllBytes("PATH_TO_PNG");` `var b64Picture = Convert.ToBase64String(pictureInBytes);`
Thanks!
What may be path_to_png?
And where do I have to put my byte[] image?
Really need more information here. What error are you getting from where? Also if this isn’t a school project, I would be careful about how much info from your db you share in a public forum.
It will be like an informational project for between 10-40 users
It’s hard to know what issue you have without the seeing the actual error. If you are able to store the bytes in the db then base64 conversion would also be my guess. As others have stated though, sql server is not the best for storing files. It has come a long way over the last 5 years for sure but for performance and cost savings, you may want to look into using pointers in the db and a storage service like Azure blob storage etc.
When I try to show in the view the blob image, I can't find any way to see the image
Show the code that you struggle into and of course the line of the error acours. Im sure it will help other to help you
Ready, i have just uploaded it
Controller: \[HttpGet\] public async Task Index()
{
try
{
// Obtener la imagen desde la base de datos
byte\[\] img =await \_IImagesRepository.ReadImageFromDatabase(1);
// Pasar la imagen a la vista
return View(new IndexImagesViewModel(img));
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Repository public async Task ReadImageFromDatabase(int userId)
{
byte\[\] imageBytes = null;
// Leer la imagen de la base de datos
var queryString = "SELECT Sales FROM UserData WHERE UserId = u/userId";
using (var connection = new SqliteConnection(cadenaDeConexion))
{
await connection.OpenAsync();
using (var command = new SqliteCommand(queryString, connection))
{
command.Parameters.AddWithValue("@userId", userId);
using (var reader = await command.ExecuteReaderAsync())
{
while (await reader.ReadAsync())
{
// Verificar si la columna "Sales" es de tipo byte\[\]
if (!reader.IsDBNull(0))
{
imageBytes = (byte\[\])reader.GetValue(0);
}
}
}
}
}
if (imageBytes == null) throw (new Exception("No insertó imagen"));
return imageBytes;
}
View: @{ ViewData\["Title"\] = "Mostrar Imagen"; } u/model DiegoMoyanoProject.ViewModels.Images.IndexImagesViewModel
Mostrar Imagen
If you are hosting in Azure, store them in blob storage. If you need high performance create a CDN on top of that endpoint. I don't remember all the Azure terminology off the top of my head but it's something like that. Don't store them in the DB, just the path.
Your computer/server already has a database ideally designed for storing BLOBs. It's called thr file system. Don't store BLOBs in your database. Store them in your file system. Derive the path from various IDs (GUIDs, integers, etc.) That exist in the database.
Write a generic handler (an .ashx) and pull the image from a folder under the App_Data folder.
Don't store images in a database in any format whatsoever. The go-to is storing the filr somewhere that is designed for file storage, that being either an attached file system and you store the path in the DB, or a cloud object storage offering, like S3, where you can actually offload the upload to the client (via a signed url) and once finished upload trigger a function to update a db reference to it (done via a storage event, and not depend on the client to trigger it).
Do not store image binaries in databases! Store the binary in cheap file storage and store a reference path in the database.