本文介绍了将pdf文件保存到SQL Server并将其显示回VB.Net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在做一个项目,这是我想做的事情:

1.允许用户浏览pdf文件,并且该pdf文件将保存到sql服务器数据库中.

2.在sql服务器的datagridview中显示该数据,如果用户选择该pdf文件的数据行,它将打开该文件或下载该文件.

任务1已经完成,但是第二个任务很艰辛,您能对如何做到这一点有所了解吗,也许您会介意帮助我共享一些代码吗?请先谢谢.

这是第一部分中的代码.

Hi guys,

I am working on a project and here''s what i want to do:

1. to allow a user to browse a pdf file and that pdf file will be saved to the sql server database.

2. to display that data in a datagridview from the sql server and if a the user selects the row of data of that pdf file it will open that file or it will download that file.

task 1 is complete but im having a hard time on the 2nd one, can you give some idea on how to this, would you guys mind helping me out share some code maybe? please, thanks in advance.

here is the code on the first part.

Private Sub bsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bsave.Click
        SavePDFtoDB()
    End Sub

Private Sub bbrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bbrowse.Click
        openfd.InitialDirectory = "C:\"
        openfd.Title = "Open a PDF file"
        openfd.Filter = "PDF files|*.pdf"
        openfd.ShowDialog()
        TextBox1.Text = openfd.FileName
    End Sub

Private Sub SavePDFtoDB()
        Try
            Dim sqlconn As SqlConnection
            Dim conn As String = "Data Source=myComputer\SQLEXPRESS;Initial Catalog=dbsample;Integrated Security=SSPI;"
            sqlconn = New SqlConnection(conn)
            Dim sqlquery As New SqlCommand

            Dim fInfo As New FileInfo(TextBox1.Text)
            Dim numBytes As Long = fInfo.Length
            Dim fStream As New FileStream(TextBox1.Text, FileMode.Open, FileAccess.Read)
            Dim br As New BinaryReader(fStream)
            Dim data As Byte() = br.ReadBytes(CInt(numBytes))
            br.Close()
            fStream.Close()

            'Insert the details into the database
            sqlquery.Connection = sqlconn
            sqlconn.Open()
            sqlquery.CommandText = "INSERT INTO tbldocument(filename, extension, content)VALUES(@filename, @extension, @content)"
            sqlquery.Parameters.Add(New System.Data.SqlClient.SqlParameter("@filename", TextBox1.Text))
            sqlquery.Parameters.Add(New System.Data.SqlClient.SqlParameter("@extension", ".pdf"))
            sqlquery.Parameters.Add(New System.Data.SqlClient.SqlParameter("@content", data))
            sqlquery.ExecuteNonQuery()
            sqlconn.Close()
            MsgBox("Saved")
        Catch err As Exception
            MsgBox(err.Message)
        End Try
    End Sub

推荐答案

/// <summary>
/// Add a download file's information to a table row.
/// </summary>
/// <param name="dl"></param>
/// <returns></returns>
private static HtmlTableRow AddDownloadFile(Downloadable dl)
    {
    HtmlTableRow row = new HtmlTableRow();
    // File name
    HtmlTableCell cell = new HtmlTableCell();
    cell.InnerHtml = "<a href=\"FileTransferDownload.aspx?file=" + dl.Id + "\" target=\"_blank\">" + dl.FileName + "</a>";
    row.Cells.Add(cell);
    // Version
    cell = new HtmlTableCell();
    cell.InnerText = dl.Version.ToString();
    row.Cells.Add(cell);
    // Upload date
    cell = new HtmlTableCell();
    cell.InnerText = dl.UploadedOn.ToString();
    row.Cells.Add(cell);
    return row;
    }


然后从数据库中获取文件,并在aspx文件中开始下载:


And then fetch the file from the DB and start the download in the aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileTransferDownload.aspx.cs" Inherits="FileTransferDownload" %>

<%
    // Send a download file to the client given the filename.    
    string guid = Request.QueryString["file"];
    string fileName = "ERROR";
    byte[] data = new byte[] { 0, 0, 0, 0 };
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DownloadDatabase"].ConnectionString;
    using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon))
        {
        con.Open();
        string strcmd = "SELECT [iD] ,cn.[fileName],[description] ,[dataContent] ,[version] " +
                        "FROM dlContent cn " +

                        "WHERE cn.iD=@ID";
        using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strcmd, con))
            {
            cmd.Parameters.AddWithValue("@ID", guid);
            using (System.Data.SqlClient.SqlDataReader r = cmd.ExecuteReader())
                {
                if (r.Read())
                    {
                    fileName = (string) r["filename"];
                    data = (byte[]) r["dataContent"];
                    }
                }
            }
        }
    Response.Clear();
    Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
    Response.AddHeader("Pragma", "no-cache");
    Response.AddHeader("Content-Description", "File Download");
    Response.AddHeader("Content-Type", "application/force-download");
    Response.AddHeader("Content-Transfer-Encoding", "binary\n");
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
    Response.BinaryWrite(data);
    //Response.WriteFile("wm5ftdata/" + fileName);
    Response.End();
%>


.CS文件几乎为空:


The .CS file is pretty much empty:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class FileTransferDownload : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {

        }
    }


报价:

cmd = New OleDbCommand(从tb_pdf中选择*,其中id_pdf ="& txt_cari.Text&", pasoe)
rd = cmd.ExecuteReader
rd.Read()
如果是rd.HasRows然后
Dim fs As FileStream = Nothing
Dim ds As DataSet
Dim temp As String ="E:\ Referensi Vb.Net \ upup dan tampil pdf \ file \" + txt_cari.Text
adp = New OleDbDataAdapter(从tb_pdf中选择*,其中id_pdf ="& txt_cari.Text&"",pasoe)
ds =新数据集
adp.Fill(ds,"tb_pdf")
将myRow变暗为DataRow
myRow = ds.Tables("tb_pdf").Rows(0)
昏暗的DataPDF()以字节为单位
DataPDF = myRow("pdf")
调光计数器只要
计数器= UBound(DataPDF)
fs =新建FileStream(temp,FileMode.OpenOrCreate,FileAccess.Write)
fs.Write(DataPDF,0,Counter)
fs.Close()
adp.Dispose()
AxAcroPDF1.src =(临时)
AxAcroPDF1.Refresh()
''WebBrowser1.Refresh()
''WebBrowser1.Navigate(temp)
其他
MsgBox("aaa")
bersih()
如果结束

cmd = New OleDbCommand("select * from tb_pdf where id_pdf =''" & txt_cari.Text & "''", pasoe)
rd = cmd.ExecuteReader
rd.Read()
If rd.HasRows Then
Dim fs As FileStream = Nothing
Dim ds As DataSet
Dim temp As String = "E:\Referensi Vb.Net\upload dan tampil pdf\file\" + txt_cari.Text
adp = New OleDbDataAdapter("select * from tb_pdf where id_pdf =''" & txt_cari.Text & "''", pasoe)
ds = New DataSet
adp.Fill(ds, "tb_pdf")
Dim myRow As DataRow
myRow = ds.Tables("tb_pdf").Rows(0)
Dim DataPDF() As Byte
DataPDF = myRow("pdf")
Dim Counter As Long
Counter = UBound(DataPDF)
fs = New FileStream(temp, FileMode.OpenOrCreate, FileAccess.Write)
fs.Write(DataPDF, 0, Counter)
fs.Close()
adp.Dispose()
AxAcroPDF1.src = (temp)
AxAcroPDF1.Refresh()
''WebBrowser1.Refresh()
''WebBrowser1.Navigate(temp)
Else
MsgBox("aaa")
bersih()
End If


这篇关于将pdf文件保存到SQL Server并将其显示回VB.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 07:40