【问题标题】:Why is my PDF contents not displaying in my Literal control?为什么我的 PDF 内容没有显示在我的 Literal 控件中?
【发布时间】:2016-03-29 16:06:15
【问题描述】:

我正在 SQL Server Management Studio 中保存数据库文件。我有一个显示存储在我的数据库中的 PDF 文件的 gridview 控件。我还有一个链接按钮“查看”,假设可以查看相应的文件。我遇到的问题是内容没有显示在我的文字控制中。编辑:我仍然无法在我的文字控件中显示内容。我收到错误消息:不存在数据时尝试读取无效。我得到的错误是在这一行: 字节=(字节[])sdr[“附件”]; 我不太确定还能尝试什么,但这是我到目前为止的代码:

这是我调用的处理程序,它使用来自 QueryString 的 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 SupportDocID=@SupportDocID";
            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;
    }
}
}

这是在我的 gridview 中单击链接按钮时处理我的链接按钮的代码:

 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);

    }

此代码将文件上传到我的数据库:

 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);
  }

我在这方面到处都看过,完全没有运气。任何帮助我都会非常感激!!!再次感谢!!!!!!

【问题讨论】:

  • 什么字面控制?哪一行抛出错误?
  • 在这一行抛出错误:int id = int.Parse(context.Request.QueryString["id"]);
  • 当这种情况发生时,context.Request.QueryString["id"] 中的内容是什么?该错误似乎暗示它是null
  • 我犯了一个错误,它实际上在 int id = int.Parse(context.Request.QueryString["SupportDocID"]);它拿着一个身份证号码。现在在我的数据库中,我有 4 个 PDF 文档。 1 到 4。
  • 你如何确认“它持有一个身份证号码”?如果错误表明它不是,那么它可能不是。

标签: c# asp.net pdf


【解决方案1】:

这一行(以及其他喜欢的行):

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

假设数据读取器中存在数据。但是,如果此行返回false

sdr.Read();

然后没有找到记录。因此,错误告诉您您正在尝试读取不存在的记录。这类似于尝试读取空数组的第一个元素 (emptyArray[0])。

您可以使用来自sdr.Read()bool 返回值来确定记录是否存在,然后再尝试读取该记录。如果您只期望一条记录(代码暗示),那么这样的事情应该可以工作:

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?
}

else 块中的操作由您决定。也许向用户返回错误消息?也许执行另一个查询以向用户返回一些“默认”PDF?还有什么?但是,您要处理错误情况取决于您希望系统的行为方式。关键是存在潜在的错误情况,您需要检查它。

最终,请求的记录不存在。所以代码需要能够解决这个问题。

【讨论】:

  • 我发现了问题,问题出在我的 Button2_Click 事件中。我应该使用: int id = int.Parse((sender as LinkBut​​ton).CommandArgument);而不是: int id = Convert.ToInt32(Request.QueryString["SupportDocID"]);我最初使用它,但我在处理程序中使用的查询字符串 id 设置为 SupportDocID 而不是 id。我确实为我的读者添加了 if else 语句。谢谢大卫!
【解决方案2】:
int id = Convert.ToInt32(Request.QueryString["Id"]);

而不是

int id = Convert.ToInt32(Request.QueryString["SupportDocID"]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多