I am learning React and I learned how to fetch an image from an API. The API fetches a byte array from an sqlite database and it creates a FileContentResult. In react it fetches via the blob function(await response.blob) and it creates an url that you can use in React. So far it is pretty straightforward with no problems. The problem comes when I am trying to fetch a list of FileContentResult. What would be the most practical way of doing it? Is it to do a fetch json and get the base64 string in each of them or is there a better way of doing it? I have heard that This is the code that works with one picture. How would I modify it to work with multiple pictures.
//private static List<FileContentResult > items = new List<FileContentResult >();
[HttpGet]
public ActionResult<IEnumerable<FileContentResult>> GetPicture()
{
try
{
string query = "SELECT * FROM pictures";
using var getconnection = new SqliteConnection(@"Data Source=picturedatabase.db");
getconnection.Open();
using var command = new SqliteCommand(query, getconnection);
using var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//var id = reader.GetInt32(0);
//var filename = reader.GetString(1);
var image = (System.Byte[])reader[2];
FileContentResult imageToReact = ByteToImage(image);
return imageToReact;
}
}
}
catch { }
//This is just a placeholder, don't worry about it for now
return null;
}
public FileContentResult ByteToImage(byte[] imageBytes)
{
return File(imageBytes, "image/png");
}
const [selectedBlob, setSelectedBlob] = useState(null);
useEffect(() => {
const fetchImage = async () => {
try {
const response = await fetch('https://localhost:7037/api/Picture');
if (response.ok) {
const data = await response.blob();
setSelectedBlob(URL.createObjectURL(data));
} else {
console.error("Error fetching image:", response.statusText);
}
} catch (error) {
console.error("Error fetching image:", error);
}
};
fetchImage();
}, []);
I tried to fetch the list with response.blob and that just creates a blob of the list.
cooolsson is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.