2016-03-29 14 views
-1

Veritabanı dosyalarını SQL Server Management Studio'da kaydediyorum. Veritabanımda saklanan PDF dosyalarını görüntüleyen bir gridview denetimim var. Ayrıca ilgili dosyaya görüntülemek için varsayalım bir "View" linkbutton var. Sahip olduğum sorun, içeriklerin benim edebi kontrolümde gösterilmemesi. DÜZENLEME: İçeriği edebi kontrolümde göstermesi için hala sorun yaşıyorum. Hatayı alıyorum: Veri yokken okumak için geçersiz girişim. Aldığım hata şu satırda: bayt = (bayt []) sdr ["Ek"]; Başka ne denemem gerektiğinden emin değilim ama şu ana kadar sahip olduğum kodum:PDF içeriğim neden Literal denetimimde görüntülenmiyor?

Bu, QueryString'den kimliği kullanan çağrıcımdır. Dosya verilerini almak için varsayalım.

: Bu kod benim veritabanına dosyası yükler

protected void Button2_Click(object sender, EventArgs e) 
    { 

     //int id = int.Parse((sender as LinkButton).CommandArgument); 
     int id = Convert.ToInt32(Request.QueryString["SupportDocID"]); 
     string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"500%\" height=\"600px\">"; 
     embed += "If you are unable to view file, you can download from <a href = \"{0}{1}&download=1\">here</a>"; 
     embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file."; 
     embed += "</object>"; 

     ltEmbed.Text = string.Format(embed, ResolveUrl("~/FileCS.ashx?Id="), id); 

    } 

:

public class FileCS : IHttpHandler 
{ 
public void ProcessRequest(HttpContext context) 
{ 
    int id = int.Parse(context.Request.QueryString["id"]); 
    byte[] bytes; 
    string fileName, contentType; 
    string constr = ConfigurationManager.ConnectionStrings["PALM3ConnectionString2"].ConnectionString; 
    using (SqlConnection con = new SqlConnection(constr)) 
    { 
     using (SqlCommand cmd = new SqlCommand()) 
     { 
      cmd.CommandText = "SELECT Attachment FROM Support_Doc WHERE [email protected]"; 
      cmd.Parameters.AddWithValue("@SupportDocID", id); 
      cmd.Connection = con; 
      con.Open(); 
      using (SqlDataReader sdr = cmd.ExecuteReader()) 
      { 
       sdr.Read(); 
       bytes = (byte[])sdr["Attachment"]; 
       contentType = sdr["Name"].ToString(); 
       fileName = sdr["Type"].ToString(); 

      } 
      con.Close(); 
     } 
    } 
    context.Response.Buffer = true; 
    context.Response.Charset = ""; 
    if (context.Request.QueryString["download"] == "1") 
    { 
     context.Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName); 
    } 
    context.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    context.Response.ContentType = "application/pdf"; 
    context.Response.BinaryWrite(bytes); 
    context.Response.Flush(); 
    context.Response.End(); 
} 
public bool IsReusable 
{ 
    get 
    { 
     return false; 
    } 
} 
} 

Bu benim GRIDVIEW içine tıklandığında benim linkbutton işlemek için benim kodudur: İşte benim işleyicisi kodudur

protected void Button1_Click(object sender, EventArgs e) 
    { 
     string filename = Path.GetFileName(FileUpload1.PostedFile.FileName); 
     string contentType = FileUpload1.PostedFile.ContentType; 
     using (Stream fs = FileUpload1.PostedFile.InputStream) 
     { 
      using (BinaryReader br = new BinaryReader(fs)) 
      { 
       byte[] bytes = br.ReadBytes((Int32)fs.Length); 
       using (SqlConnection con = Connection.GetConnection()) 
       { 
        //using (SqlCommand com = new SqlCommand()) 
        //{ 

         // com.CommandText = "UploadDoc"; 
         //com.CommandType = CommandType.StoredProcedure; 
        string query = "insert into Support_Doc values (@Type, @Name, @Attachment)"; 
        using (SqlCommand com = new SqlCommand(query)){ 
         com.Connection = con; 
         com.Parameters.AddWithValue("@Type", filename); 
         com.Parameters.AddWithValue("@Name", contentType); 
         com.Parameters.AddWithValue("@Attachment", bytes); 
         con.Open(); 
         com.ExecuteNonQuery(); 
         Label1.ForeColor = System.Drawing.Color.Green; 
         Label1.Text = "File Uploaded Successfully!"; 
         con.Close(); 
        } 

       } 
      } 
     } 
     Response.Redirect(Request.Url.AbsoluteUri); 
    } 

Bu konuda her yerde kesinlikle hiçbir şansla baktım. Herhangi bir yardım soooo minnettar olacağım! Tekrar teşekkürler!!!!!

+0

Hangi gerçek denetim? Hangi satır hatayı atar? – David

+0

Bu satırdaki hatayı atar: int id = int.Parse (context.Request.QueryString ["id"]); – user3474069

+0

Ve bu olduğunda context.Request.QueryString ["id"] 'de ne var? Hata, 'null' olduğunu ima eder gibi görünüyor. – David

cevap

0

Bu hat (ve bunun gibi diğer):

bytes = (byte[])sdr["Attachment"]; 

verileri veri okuyucu mevcut olduğunu varsayar. Ancak, bu hat false dönerse:
sdr.Read(); 

sonra hiçbir kayıt bulunamadı. Yani hata, orada olmayan bir kaydı okumaya çalıştığınızı söylüyor. Boş bir dizinin ilk elemanını okumaya benzer ( emptyArray[0]).

sdr.Read() numaralı bool dönüş değerini, bu kaydı okumaya çalışmadan önce kaydın olup olmadığını belirlemek için kullanabilirsiniz. Tam olarak (kod ima) bir kayıt bekliyorsanız sonra böyle bir şey çalışması gerekir: Ne else blokta yapılacak size kalmış

if (sdr.Read()) 
{ 
    bytes = (byte[])sdr["Attachment"]; 
    contentType = sdr["Name"].ToString(); 
    fileName = sdr["Type"].ToString(); 
} 
else 
{ 
    // no record was found, how do you want to proceed? 
} 

. Belki kullanıcıya bir hata mesajı gönderilsin mi? Belki kullanıcı için bazı "varsayılan" PDF döndürmek için başka bir sorgu yürütmek? Başka bir şey? Ancak, hata koşulunu ele almak istediğinizde sistemin nasıl davranmasını istediğinize bağlıdır. Önemli nokta, olası bir hata durumunun mevcut olmasıdır ve bunu kontrol etmeniz gerekmektedir. Son olarak, mevcut olmayan bir kayıt isteniyor. Bu yüzden kodun bunu hesaba katması gerekiyor.

+0

Sorunu buldum, sorun Button2_Click etkinliğimdi. Kullanmalıydım: int id = int.Parse ((gönderici olarak LinkButton) .CommandArgument); yerine: int id = Dönüştür.ToInt32 (Request.QueryString ["SupportDocID"]); Orijinal olarak kullanıyordum ancak işleyicimde kullandığım querystring kimliğim id yerine SupportDocID olarak ayarlandı. Okuyucu için başka bir ifade ekledim. Teşekkürler David! – user3474069

İlgili konular