-1

I want to fetch an image from the database and show it in my react-native app.where I did go wrong?

public IActionResult DownloadFile(int id)
{
    DataTable table = new DataTable();
    string query = @"select image from mydb.courses where id=@id";
    string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
    MySqlDataReader myReader;
    using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myReader = myCommand.ExecuteReader();
            table.Load(myReader);
            var fs = new FileStream(myReader, FileMode.Open);
            return File(fs, "application/octet-stream");
            myReader.Close();
            mycon.Close();
        }
    }
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ali Mahmoudi
  • 83
  • 2
  • 8
  • 1
    `return` will prevent the `close()` from being called. To return an image look at: https://stackoverflow.com/questions/39177576/how-to-to-return-an-image-with-web-api-get-method/39177684 – Greg Oct 09 '21 at 11:08
  • Hi @Ali Mahmoudi, What is the error message? Could you please share your react component? – Rena Oct 11 '21 at 08:40
  • Hi Greg and @Rena, I fixed it – Ali Mahmoudi Oct 11 '21 at 09:17

1 Answers1

-1

I fixed it.

[HttpGet("{id}")]
public IActionResult DownloadFile(int id)
{
    string pathImage = "";
    DataTable table = new DataTable();
    string query = @"select image from mydb.courses where id=@id";
    string sqlDataSource = _configuration.GetConnectionString("UsersAppCon");
    MySqlDataReader myReader;
    using (MySqlConnection mycon = new MySqlConnection(sqlDataSource))
    {
        mycon.Open();
        using (MySqlCommand myCommand = new MySqlCommand(query, mycon))
        {
            myCommand.Parameters.AddWithValue("@id", id);
            pathImage = (string)myCommand.ExecuteScalar();
            mycon.Close();
        }
    }
    var path = @$"{pathImage}";
    var fs = new FileStream(path, FileMode.Open);
    return File(fs, "image/jpeg");
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ali Mahmoudi
  • 83
  • 2
  • 8