C
C#ā€¢5mo ago
MarcoART_

How to insert an image from a MediaPicker into my database in C# (MAUI)

Hello! šŸ™‚ I'm new to MAUI and I'm facing challenges trying to insert an image from a MediaPicker into my database. What I do is obtain either my byte array using these lines:
await stream.CopyToAsync(memoryStream);
ImageData = memoryStream.ToArray();
photoPreview.Source = ImageSource.FromStream(() => new MemoryStream(ImageData));
await stream.CopyToAsync(memoryStream);
ImageData = memoryStream.ToArray();
photoPreview.Source = ImageSource.FromStream(() => new MemoryStream(ImageData));
or obtain the data in a base64 string value using this line:
base64string = Convert.ToBase64String(ImageData);
base64string = Convert.ToBase64String(ImageData);
The problem is, once I obtain these values that I need to insert into my database, and I execute the insert query, I'm getting this error: Microsoft.Data.SqlClient.SqlException: 'A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - Success)' This only happens if i'm including the image in the query, if I eliminate it, the other data can be inserted perfectly without showing me any error. This is my query:
byte[] bytesImagen = Convert.FromBase64String(base64string);

string cadena = @"Insert into Marco.CatUsuarios (Usuario, Nombre, Contrasena, NumTelefono, Imagen2, Ubicacion, Longitud, Latitud) values (@Usuario, @Nombre, @Contrasena, @NumTelefono, @Imagen2, @Ubicacion, @Longitud, @Latitud)";
SqlCommand comando = new SqlCommand(cadena, conexion);

comando.Parameters.AddWithValue("@Usuario", Usuario.Text);
comando.Parameters.AddWithValue("@Nombre", Nombre.Text);
comando.Parameters.AddWithValue("@Contrasena", Contrasena.Text);
comando.Parameters.AddWithValue("@NumTelefono", NumTelefono.Text);
comando.Parameters.AddWithValue("@Imagen2", bytesImagen);

comando.ExecuteNonQuery();
byte[] bytesImagen = Convert.FromBase64String(base64string);

string cadena = @"Insert into Marco.CatUsuarios (Usuario, Nombre, Contrasena, NumTelefono, Imagen2, Ubicacion, Longitud, Latitud) values (@Usuario, @Nombre, @Contrasena, @NumTelefono, @Imagen2, @Ubicacion, @Longitud, @Latitud)";
SqlCommand comando = new SqlCommand(cadena, conexion);

comando.Parameters.AddWithValue("@Usuario", Usuario.Text);
comando.Parameters.AddWithValue("@Nombre", Nombre.Text);
comando.Parameters.AddWithValue("@Contrasena", Contrasena.Text);
comando.Parameters.AddWithValue("@NumTelefono", NumTelefono.Text);
comando.Parameters.AddWithValue("@Imagen2", bytesImagen);

comando.ExecuteNonQuery();
And this is my connection string:
string connectionString = "Data Source=MyDataSource;Initial Catalog=MyInitialCatalog; User ID= MyUserID; Password = MyPassword; TrustServerCertificate=true;";
string connectionString = "Data Source=MyDataSource;Initial Catalog=MyInitialCatalog; User ID= MyUserID; Password = MyPassword; TrustServerCertificate=true;";
Thank You!
12 Replies
SuperBrain
SuperBrainā€¢5mo ago
General rule is to never store images in database, but rather a path to an image on the file system.
MarcoART_
MarcoART_ā€¢5mo ago
Well, in my case, what I'm doing is allowing a user to register information along with an image. My goal is for all devices to access this user-entered information and also view the image, which is why I was trying to save the image in my database. If I save only the path, when retrieving the information, the path will only work for the device that uploaded the file, and others won't be able to view it. I should also mention that if I generate the query within my database manager and execute it, the data is inserted without any issues. The error only occurs when I do it from the app.
Tarcisio
Tarcisioā€¢5mo ago
That's why you save it either in a cdn or to your own filesystem, and then make it available for the user as an image itself And not as a path Unless you're using a cdn, then you can provide the url to the application
SuperBrain
SuperBrainā€¢5mo ago
Typically, you store uploaded images on the same machine where your database is stored. So, when users upload an image, you save it in your file system and then write the path to that image in your database. Whenever someone wants to see the image, you use the stored path to serve the same image from your file system.
MarcoART_
MarcoART_ā€¢5mo ago
So, if the user takes a photo from their cellphone, then I store the image in the system and save the path in the database, upon retrieving this path, can any device view it even if this device didn't take the photo?
SuperBrain
SuperBrainā€¢5mo ago
Where is your database located? Is it on the server somewhere? Or does every device have their own database?
MarcoART_
MarcoART_ā€¢5mo ago
The database is on a hosting server.
SuperBrain
SuperBrainā€¢5mo ago
So that's where you should be uploading the images too. Paths stored in database should point to images stored there.
MarcoART_
MarcoART_ā€¢5mo ago
Perfect! Thank you for your help
Yawnder
Yawnderā€¢5mo ago
@MarcoART_ Just want to point out that if you're going to host on services like Azure, where you can't access the filesystem of the the database server (in 99% of the cases, but for now let's assume), you might want to store the image in a Blob, either public or private. If private, your application can then easily generate urls to serve that image without you hitting the blob since you know the exact path.
Tarcisio
Tarcisioā€¢5mo ago
Backblaze B2 is pretty much "free" for small applications btw
MarcoART_
MarcoART_ā€¢5mo ago
Thank you!
Want results from more Discord servers?
Add your server
More Posts
I need some help with attributeWelp I don't know much about attribute and GPT keeps sending me s*** code Anyone can give me an exaSystem.NullReferenceException: Object reference not set to an instance of an object.I'm developing a Asp.net Api which consist in the updating a existing Object into another, but when āœ… Setting app's address (Blazor 8 SSR)I have created a Blazor 8 wasm+ssr app, but after deployment my redirects broke. The app is hostedāœ… How to Retrieve the Selected Item Value from a ComboBox in C# (AvaloniaUI)Hi, How can I get the value of the selected item in a ComboBox in C# (I'm using AvaloniaUI), please?Change function behavior depending on class' generic type.Hello! I was wondering if there was a way to change the behavior of a function in a class with a geGet my Webcam picture using AForge.netHi, so I want to make a simple file called getpic.cs with class called Module and a function Shot() Working on a school projectHey! So iā€™m working on musically themed class project where we are supposed to create a database usPairing Visual Studio (Windows) to a Mac to build an app remotely on the MacWhen I try to connect my Visual Studio to a Mac device I get stuck on the display of the message froBuild Errors after updating Visual StudioHi, this is a Net 6.0 MAUI application, which I could build and run without issues 30 minutes ago. IPropagate Changes to WPFI'm using WPF with Unity Container and Prism. I've got a save button which is supposed to activate o