asp.net网页中上传并且浏览pdf文件的实现

本文主要讲解在asp.net中的gridview中浏览pdf文件。下面来看一下具体的实现:

第一步,使用sqlserver 创建一个数据库表。

第二步,新建一个webform,命名为uploadpdf.aspx。

第三步,在该页面中添加一个upload控件,两个button控件,代码如下。

     <asp:fileupload ID="Fileupload1" runat="server"></asp:fileupload>
     <asp:Button ID="Btnupload" runat="server" Text="上传" οnclick="Btnupload_Click" />
     <asp:Button ID="Btncancel"  runat="server" Text="取消" />
     <asp:Label ID="alert" runat="server" />

 

第四步,单击上传按钮在Btnupload_Click事件中写入上传代码。

try
            {
                byte[] pdf = null;
                if (Fileupload1.HasFile & Fileupload1.PostedFile != null)//判断上传文件是否为空
                {
                    HttpPostedFile file = Fileupload1.PostedFile;
                    pdf = new byte[file.ContentLength];//创建一个文件长度的字节数组
                    file.InputStream.Read(pdf, 0, file.ContentLength);//把文件写入二进制字节数组pdf中
                   
                }

                string connectionStr = System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
                SqlConnection con = new SqlConnection(connectionStr);
                con.Open();
                string sql = "insert into tbl_pdf (pdfFile,FileName) values(@pdfFile,@FileName)";
                SqlCommand cmd = new SqlCommand(sql, con);
                cmd.Parameters.AddWithValue("@pdfFile", pdf);
                cmd.Parameters.AddWithValue("@FileName", Fileupload1.PostedFile.FileName);
                cmd.ExecuteNonQuery();
                alert.Text = "file uploaded successfully";
                con.Close();

            }
            catch (Exception ex) 
            {
                Response.Write(ex.Message);
            }

到这里,可以上传pdf文件保存到数据库中。

第五步,在uploadpdf.aspx添加一个gridview控件和一个数据源控件。

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        DataSourceID="pdfview">
        <Columns>
            <asp:BoundField DataField="Doc_ID" HeaderText="Doc_ID" InsertVisible="False" 
                ReadOnly="True" SortExpression="Doc_ID" />
            <asp:BoundField DataField="FileName" HeaderText="FileName" 
                SortExpression="FileName" />
            <asp:TemplateField>  
             <ItemTemplate>  
                 <asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="VIEW"  CommandArgument='<%# Eval("Doc_ID") %>'></asp:LinkButton>              </ItemTemplate>  
           </asp:TemplateField>  

        </Columns>
    </asp:GridView>
    <asp:SqlDataSource ID="pdfview" runat="server" 
        ConnectionString="<%$ ConnectionStrings:testConnectionString %>" 
        SelectCommand="SELECT * FROM [tbl_pdf]"></asp:SqlDataSource>

第六步,新建一个处理程序来读取pdf文件。

第七步,在新建的处理程序下面添加处理代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace test
{
    /// <summary>
    /// Pdfhandler 的摘要说明
    /// </summary>
    public class Pdfhandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            Int32 theID;
            if (context.Request.QueryString["id"] != null)
                theID = Convert.ToInt32(context.Request.QueryString["id"]);
            else
                throw new ArgumentException("no parameter specified");
            context.Response.ContentType = "Application/pdf";
            Stream  strm = DisplayImage(theID) ;
            byte[] buffer = new byte[2048];
            int byteseq = strm.Read(buffer,0,2048);
            while (byteseq > 0) 
            {
                context.Response.OutputStream.Write(buffer, 0, byteseq);
                byteseq = strm.Read(buffer, 0, 2048);
            }
           
        }
        public Stream DisplayImage(int theID) 
        {
            string str = System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(str);
            string sql = "SELECT pdfFile FROM [tbl_pdf] where Doc_ID = @Doc_ID ";
            SqlCommand cmd = new SqlCommand(sql,con);
            cmd.Parameters.AddWithValue("Doc_ID",theID);
            con.Open();
            object theImg = cmd.ExecuteScalar();
            try
            {
                return new MemoryStream((byte[])theImg);
            }
            catch
            {

                return null;
            }
            finally 
            {
                con.Close();
            }
        }
View Code

第八步,这时应该在gridview中添加一个linkbutton点击连接查看。

<asp:TemplateField>  
             <ItemTemplate>  
                   <asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="VIEW"  CommandArgument='<%# Eval("Doc_ID") %>'></asp:LinkButton>  
             </ItemTemplate>  
</asp:TemplateField>  

第九步,在uploadpdf.aspx.cs下面新建一个点击链接的方法。

       public void VIEW(object sender, EventArgs e) 
        {
            int id = int.Parse((sender as LinkButton).CommandArgument);
            Response.Redirect("Pdfhandler.ashx?Id="+id+"");
            
        }

到这里就大功告成,然后进行测试。

测试结果如下

点击view连接,这时结果如下。

 

转载于:https://www.cnblogs.com/Hackerman/p/4204881.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
【核心代码】 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 using Aspose.Cells; using Aspose.Slides.Pptx; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; namespace DocOnlineView.UI.Controllers.MVCAPI { public class HomeController : ApiController { [HttpGet] public DataTable CourseViewOnLine(string fileName) { DataTable dtlist = new DataTable(); dtlist.Columns.Add("TempDocHtml", typeof(string)); string fileDire = "/Files"; string sourceDoc = Path.Combine(fileDire, fileName); string saveDoc = ""; string docExtendName = System.IO.Path.GetExtension(sourceDoc).ToLower(); bool result = false; if (docExtendName == ".pdf") { //pdf模板文件 string tempFile = Path.Combine(fileDire, "temppdf.html"); saveDoc = Path.Combine(fileDire, "viewFiles/onlinepdf.html"); result = PdfToHtml( sourceDoc, System.Web.HttpContext.Current.Server.MapPath(tempFile), System.Web.HttpContext.Current.Server.MapPath(saveDoc)); } else { saveDoc = Path.Combine(fileDire, "viewFiles/onlineview.html"); result = OfficeDocumentToHtml( System.Web.HttpContext.Current.Server.MapPath(sourceDoc), System.Web.HttpContext.Current.Server.MapPath(saveDoc)); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值