Click here to Skip to main content
15,914,488 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
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.
VB
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
Posted
Updated 11-Nov-20 19:14pm
v3

I use a similar system, but not just for PDF files.
The way I do it is to put a link to an aspx file as my table link:

C#
/// <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;
    }

And then fetch the file from the DB and start the download in the aspx file:
ASP.NET
<%@ 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();  
%>

The .CS file is pretty much empty:
C#
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)
        {

        }
    }
 
Share this answer
 
Comments
Michael Sernal 25-Apr-12 10:55am    
Hi OriginalGriff,

Thanks for sharing your idea but i can't get a clear picture because im not familiar with aspx or asp.net, my bad. And oh, i'm new in code project, and i'm still looking forward from other peoples ideas, am i supposed to accept the solution? or will i save it for later? if you don't mind me asking, thanks.
OriginalGriff 25-Apr-12 12:21pm    
Accept the solution if it has solved your problem, otherwise save it for later :laugh:
coding to diplaying pdf in form .Net :
Quote:
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
 
Share this answer
 
Comments
Member 11164402 25-Oct-14 2:53am    
thanks really help full

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900