How to open a pdf file in a WebForm application by search?

后端 未结 1 1404
醉酒成梦
醉酒成梦 2021-01-29 07:51

When I click on the listbox which search a PDF file, it\'s not opening.

The code is below. Any thoughts?

protected void Button1_Click(object sender, Even         


        
相关标签:
1条回答
  • 2021-01-29 08:51

    First, you must save the file's full name to get it later. So, you must change from:

    ListBox1.Items.Add(Path.GetFileName(file));
    

    To:

    ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
    

    Then, you should send the file from the server to the client, like this:

    protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        string fileName = ListBox1.SelectedValue;
        byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);
    
        System.Web.HttpContext context = System.Web.HttpContext.Current;
        context.Response.Clear();
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.AppendHeader("content-length", fileBytes.Length.ToString());
        context.Response.ContentType = "application/pdf";
        context.Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
        context.Response.BinaryWrite(fileBytes);
        context.ApplicationInstance.CompleteRequest();
    }
    

    Note: don't forget to initialize your ListBox with the property AutoPostBack setted to true.

    0 讨论(0)
提交回复
热议问题