C
C#•12mo 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•12mo ago
General rule is to never store images in database, but rather a path to an image on the file system.
MarcoART_
MarcoART_OP•12mo 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•12mo 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•12mo 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_OP•12mo 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•12mo ago
Where is your database located? Is it on the server somewhere? Or does every device have their own database?
MarcoART_
MarcoART_OP•12mo ago
The database is on a hosting server.
SuperBrain
SuperBrain•12mo ago
So that's where you should be uploading the images too. Paths stored in database should point to images stored there.
MarcoART_
MarcoART_OP•12mo ago
Perfect! Thank you for your help
Yawnder
Yawnder•12mo 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•12mo ago
Backblaze B2 is pretty much "free" for small applications btw
MarcoART_
MarcoART_OP•12mo ago
Thank you!

Did you find this page helpful?