2017-10-18 17 views
1

Je suis nouveau à ASP & C# et n'ai pas réussi à comprendre comment faire cela.comment charger une image par défaut de .ashx lorsque SQL BLOB est indisponible

Je charge des BLOB à partir d'un bd via un fichier .ashx comme si <img src="getimage.ashx" /> et cela fonctionne très bien, mais parfois il n'y a pas de BLOB ou il est vide.

est ici le code de base

 SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DataSource.iMIS.Connection"].ConnectionString); 
     SqlCommand cmd = new SqlCommand("SELECT PICTURE_LOGO FROM Name_Picture WHERE ID = @EmpID", con); 
     cmd.CommandType = CommandType.Text; 
     cmd.Parameters.Add("@EmpID", id); 

     con.Open(); 
     byte[] pict = (byte[])cmd.ExecuteScalar(); 
     con.Close(); 

     ctx.Response.ContentType = "image/bmp"; 
     ctx.Response.OutputStream.Write(pict, 0, pict.Length); 

Ma pensée est de vérifier pict.Length juste après con.Close() et si elle échoue, je veux afficher une image par défaut, ou même texte.

Est-ce possible? Comment?

+0

Je suis tombé sur cet article, mais je ne suis pas http://www.nullskull.com/a/263/aspnet-write-image-to-responseoutputstream.aspx – Chad

+0

Je suis en train de mettre en œuvre cette https://stackoverflow.com/a/2070493/3790921 mais ne peut pas comprendre comment "stream" il – Chad

Répondre

0

Si vous souhaitez charger une image à partir du disque alors qu'aucun élément n'est trouvé dans la base de données, utilisez cet extrait.

public void ProcessRequest(HttpContext context) 
{ 
    //create a new byte array 
    byte[] pict = new byte[0]; 

    //create a connection to the db and a command 
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DataSource.iMIS.Connection"].ConnectionString)) 
    using (SqlCommand command = new SqlCommand("SELECT PICTURE_LOGO FROM Name_Picture WHERE ID = @EmpID", connection)) 
    { 
     //set the proper command type 
     command.CommandType = CommandType.Text; 

     //replace the parameters 
     command.Parameters.Add("@EmpID", SqlDbType.Int).Value = id; 

     try 
     { 
      //open the db and execute the sql string 
      connection.Open(); 
      pict = (byte[])command.ExecuteScalar(); 
     } 
     catch (Exception ex) 
     { 
      //catch any errors like unable to open db or errors in command. view with ex.Message 
     } 
    } 

    //if no image found in database load the default from disk 
    if (pict == null || pict.Length == 0) 
    { 
     pict = File.ReadAllBytes(context.Server.MapPath("/noimage.bmp")); 
    } 

    //clear the buffer stream 
    context.Response.ClearHeaders(); 
    context.Response.Clear(); 
    context.Response.Buffer = true; 

    //set the correct ContentType 
    context.Response.ContentType = "image/bmp"; 

    //set the filename for the image 
    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"ImageName.bmp\""); 

    //set the correct length of the string being send 
    context.Response.AddHeader("content-Length", pict.Length.ToString()); 

    //send the byte array to the browser 
    context.Response.OutputStream.Write(pict, 0, pict.Length); 

    //cleanup 
    context.Response.Flush(); 
    context.ApplicationInstance.CompleteRequest(); 
} 
+0

Merci! cette ligne ici 'pict = File.ReadAllBytes (context.Server.MapPath ("/noimage.bmp "));' était exactement ce dont j'avais besoin. – Chad

0

Après beaucoup plus de recherche et beaucoup de 'HttpCompileException (s)', j'ai eu ce travail.

Merci à @Kazar pour cette réponse ici https://stackoverflow.com/a/2070493/3790921 et @Pranay Rana pour cette réponse ici https://stackoverflow.com/a/3801289/3790921

Je mets cela ensemble ...

 con.Open(); 
     byte[] pict = (byte[])cmd.ExecuteScalar(); 
     con.Close(); 

     ctx.Response.ContentType = "image/bmp"; 
     if (pict.Length <= 1) { 
      // the BLOB is not a picture 
      byte[] txt = ImageToByteArray(DrawText("no image found")); 
      ctx.Response.OutputStream.Write(txt, 0, txt.Length); 
     } else { 
      // stream the picture data from BLOB 
      ctx.Response.OutputStream.Write(pict, 0, pict.Length); 
     } 

et il fonctionne.

+0

Le bonus de cette approche est que vous pourriez produire un message d'erreur et de sortie, ou changer le texte/image à la volée. – Chad