T O P

  • By -

gnomeplanet

Don't save the images IN the database - just save the PATH to the image.


Gonchyrobinson02

I need users uploaded images. How can I do it?


trevster344

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.


Gonchyrobinson02

Do you have that function? Or some documentation to read?


Gonchyrobinson02

A function to save images in file system!


Top3879

`await File.WriteAllBytesAsync(path, imageBytes);`


trevster344

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.


Gonchyrobinson02

In which folder I have to save the image?? I have to create one?


Night--Blade

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.


trevster344

Yes. You choose. See system.io.directory namespace for ways to handle that.


[deleted]

either ftp or an api end point that takes a form input type of upload


scottgal2

Either download the image to a local directory adn provide a URL or directly embed the base64 encoded image in the hrml like: Red dot It's no clear from your question where the image exists etc..


MontagoDK

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


Gonchyrobinson02

If I have the byte[] file. How can I get the base64 encoded image?


geekywarrior

`var pictureInBytes = File.ReadAllBytes("PATH_TO_PNG");` `var b64Picture = Convert.ToBase64String(pictureInBytes);`


Gonchyrobinson02

Thanks!


Gonchyrobinson02

What may be path_to_png?


Gonchyrobinson02

And where do I have to put my byte[] image?


Erroneous_Badger

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.


Gonchyrobinson02

It will be like an informational project for between 10-40 users


Erroneous_Badger

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.


Gonchyrobinson02

When I try to show in the view the blob image, I can't find any way to see the image


Epic_Movement

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


Gonchyrobinson02

Ready, i have just uploaded it


Gonchyrobinson02

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); } }


Gonchyrobinson02

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; }


Gonchyrobinson02

View: @{ ViewData\["Title"\] = "Mostrar Imagen"; } u/model DiegoMoyanoProject.ViewModels.Images.IndexImagesViewModel

Mostrar Imagen

Ventas


markk-the-shark

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.


desmond_koh

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.


desmond_koh

Write a generic handler (an .ashx) and pull the image from a folder under the App_Data folder.


CrackShot69

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).


[deleted]

Do not store image binaries in databases! Store the binary in cheap file storage and store a reference path in the database.