如何把PDF文件以二进制形式保存到数据库表中,然后再可以把读出来。

时间:2022-10-18 21:44:56
把给定路径PDF文件写入数据库,然后可以把它读出来!两个过程,高手帮忙

12 个解决方案

#1


先顶一下

#2


 用byte[]保存PDF文件,数据库里用varbinary类型保存

#3


能不能提供代码,实例!高手们

#4


如下代码把文件转成byte数组,然后把这个数组存到数据库的二进制字段中:

FileStream fs = new FileStream(path, FileMode.Open);
byte[] b=new byte[fs.Length];
fs.Read(b, 0, fs.Length);
fs.Close();


如下代码把byte数组存到文件,这个byte数组取自数据库的二进制字段:

FileStream _fs = new FileStream(path, FileAccess.Write);
_fs.Write(b, 0, b.Length);
_fs.Close();

#5


//保存
            System.Data.SqlClient.SqlConnection _Conn = new System.Data.SqlClient.SqlConnection();
            _Conn.Open();
            System.Data.SqlClient.SqlCommand _Command = new System.Data.SqlClient.SqlCommand("Insert into 表名(字段)Values(@字段)", _Conn);
            _Command.Parameters.Add(new System.Data.SqlClient.SqlParameter("@字段", SqlDbType.Image));
            _Command.Parameters[0].Value = File.ReadAllBytes("PDF文件");
            _Command.ExecuteNonQuery();
            _Conn.Close();


//读取
            System.Data.SqlClient.SqlConnection _Conn = new System.Data.SqlClient.SqlConnection();
            _Conn.Open();
            System.Data.SqlClient.SqlCommand _Command = new System.Data.SqlClient.SqlCommand("Select * from 表名", _Conn);
            System.Data.SqlClient.SqlDataReader _Read = _Command.ExecuteReader();
            byte[] _Value =(byte[]) _Read["字段"];


如果是DataTable..  可以 (byte[])DataTable.Rows[0][0] 这个把图片保存到数据库是一样的

#6


不管你是pdf还是其他的任何文件,都能通过以下方式读取为byte[]
            Stream ms;
            byte[] _byte;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            string f = ofd.FileName;

            ms = ofd.OpenFile();
            _byte = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(_byte, 0, Convert.ToInt32(ms.Length));
            SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();
            string sqlstring = "insert into ttt(file) values(@pdf)";
            SqlCommand cmd = new SqlCommand(sqlstring, conn);
            cmd.Parameters.Add("@pdf", SqlDbType.Image, _byte.Length).Value = picbyte;

#7


入库: 
           
Stream ms;
            byte[] _byte;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            string f = ofd.FileName;

            ms = ofd.OpenFile();
            _byte = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(_byte, 0, Convert.ToInt32(ms.Length));
            SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();
            string sqlstring = "insert into ttt(file) values(@pdf)";
            SqlCommand cmd = new SqlCommand(sqlstring, conn);
            cmd.Parameters.Add("@pdf", SqlDbType.Image, _byte.Length).Value = _byte;

#8


从库中读取

SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();
            string strSql = "select file from ttt ";
            SqlCommand cmd = new SqlCommand(strSql, conn);
            SqlDataReader sdr = cmd.ExecuteReader();
            sdr.Read();
            MemoryStream ms = new MemoryStream((byte[])sdr[0]);


然后把ms写入一个新文件或在程序中处理即可。
            

#9


 private void button1_Click(object sender, EventArgs e)
        {
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //上传的图片文件到Image
                Image image = Image.FromFile(openFileDialog1.FileName);
                this.pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
                // 以Jpeg格式存到内存中
                MemoryStream st = new MemoryStream();
                
                image.Save(st,System.Drawing.Imaging.ImageFormat.Jpeg);
 
                SqlCommand cmd = new SqlCommand("spInsertImage", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                // 图片的二进制数据
                cmd.Parameters.Add("@ImageBinary",SqlDbType.Image);
                cmd.Parameters["@ImageBinary"].Value = st.ToArray();
                conn.Open();
                try
                {
                    if (cmd.ExecuteNonQuery() > 0)
                    {
                       
                        MessageBox.Show("成功");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                image.Dispose();
                st.Dispose();
                st.Flush();
                cmd.Clone();
                conn.Close();
               

            }

        }

        private List<int> SelectSet()
        {
            
            string sql = "select ID from Images";
            SqlCommand  com = new SqlCommand(sql,conn);
            conn.Open();
            SqlDataReader data = com.ExecuteReader();
            info = new List<int>();
            while (data.Read())
            {
                info.Add( Int32.Parse( data["ID"].ToString()));
            }
            
            conn.Close();
            com.Clone();
            return info;
        }

        /// <summary>
        /// 从数据库中读耶图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("spSelectImage", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@ImageID", int.Parse(this.comboBox1.Text));
            cmd.Parameters["@ImageID"].Value = Int32.Parse(this.comboBox1.Text);
            
            conn.Open();
            try
            {
                SqlDataReader data = cmd.ExecuteReader();
                if (data.Read())
                {

                    byte[] photo = (byte[])data["Imagee"];
                    MemoryStream ms = new MemoryStream(photo);
                    Image img = Image.FromStream(ms);
                    this.pictureBox1.Image = img;
                    ms.Flush();
                    ms.Close();
                    data.Close();
                }

             
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            conn.Close();
            cmd.Clone();

        }
这是我写的存图片的应该和你说的那个PDF差不多吧 PDE我真没试过 呵呵  你自己看看吧能否帮到你

#10


先谢了,各位大哥们

#11


引用 7 楼 wdgphc 的回复:
入库:
         C# codeStream ms;byte[] _byte;
            OpenFileDialog ofd=new OpenFileDialog();
            ofd.ShowDialog();string f= ofd.FileName;

            ms= ofd.OpenFile();
            _byte=newbyte[ms.Length];
            ms.Position=0;
            ms.Read(_byte,0, Convert.ToInt32(ms.Length));
            SqlConnection conn=new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();string sqlstring="insert into ttt(file) values(@pdf)";
            SqlCommand cmd=new SqlCommand(sqlstring, conn);
            cmd.Parameters.Add("@pdf", SqlDbType.Image, _byte.Length).Value= _byte;


是不是少了一句: cmd.ExecuteNonQuery(); 
现在问题是,保存时,总是提示长度不够,我保存PDF数据类型用的是:varbinary(8000),已经是最大了,怎么办!

#12


先转成byte[] 然后存到image字段中

#1


先顶一下

#2


 用byte[]保存PDF文件,数据库里用varbinary类型保存

#3


能不能提供代码,实例!高手们

#4


如下代码把文件转成byte数组,然后把这个数组存到数据库的二进制字段中:

FileStream fs = new FileStream(path, FileMode.Open);
byte[] b=new byte[fs.Length];
fs.Read(b, 0, fs.Length);
fs.Close();


如下代码把byte数组存到文件,这个byte数组取自数据库的二进制字段:

FileStream _fs = new FileStream(path, FileAccess.Write);
_fs.Write(b, 0, b.Length);
_fs.Close();

#5


//保存
            System.Data.SqlClient.SqlConnection _Conn = new System.Data.SqlClient.SqlConnection();
            _Conn.Open();
            System.Data.SqlClient.SqlCommand _Command = new System.Data.SqlClient.SqlCommand("Insert into 表名(字段)Values(@字段)", _Conn);
            _Command.Parameters.Add(new System.Data.SqlClient.SqlParameter("@字段", SqlDbType.Image));
            _Command.Parameters[0].Value = File.ReadAllBytes("PDF文件");
            _Command.ExecuteNonQuery();
            _Conn.Close();


//读取
            System.Data.SqlClient.SqlConnection _Conn = new System.Data.SqlClient.SqlConnection();
            _Conn.Open();
            System.Data.SqlClient.SqlCommand _Command = new System.Data.SqlClient.SqlCommand("Select * from 表名", _Conn);
            System.Data.SqlClient.SqlDataReader _Read = _Command.ExecuteReader();
            byte[] _Value =(byte[]) _Read["字段"];


如果是DataTable..  可以 (byte[])DataTable.Rows[0][0] 这个把图片保存到数据库是一样的

#6


不管你是pdf还是其他的任何文件,都能通过以下方式读取为byte[]
            Stream ms;
            byte[] _byte;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            string f = ofd.FileName;

            ms = ofd.OpenFile();
            _byte = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(_byte, 0, Convert.ToInt32(ms.Length));
            SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();
            string sqlstring = "insert into ttt(file) values(@pdf)";
            SqlCommand cmd = new SqlCommand(sqlstring, conn);
            cmd.Parameters.Add("@pdf", SqlDbType.Image, _byte.Length).Value = picbyte;

#7


入库: 
           
Stream ms;
            byte[] _byte;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowDialog();
            string f = ofd.FileName;

            ms = ofd.OpenFile();
            _byte = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(_byte, 0, Convert.ToInt32(ms.Length));
            SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();
            string sqlstring = "insert into ttt(file) values(@pdf)";
            SqlCommand cmd = new SqlCommand(sqlstring, conn);
            cmd.Parameters.Add("@pdf", SqlDbType.Image, _byte.Length).Value = _byte;

#8


从库中读取

SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();
            string strSql = "select file from ttt ";
            SqlCommand cmd = new SqlCommand(strSql, conn);
            SqlDataReader sdr = cmd.ExecuteReader();
            sdr.Read();
            MemoryStream ms = new MemoryStream((byte[])sdr[0]);


然后把ms写入一个新文件或在程序中处理即可。
            

#9


 private void button1_Click(object sender, EventArgs e)
        {
            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                //上传的图片文件到Image
                Image image = Image.FromFile(openFileDialog1.FileName);
                this.pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);
                // 以Jpeg格式存到内存中
                MemoryStream st = new MemoryStream();
                
                image.Save(st,System.Drawing.Imaging.ImageFormat.Jpeg);
 
                SqlCommand cmd = new SqlCommand("spInsertImage", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                // 图片的二进制数据
                cmd.Parameters.Add("@ImageBinary",SqlDbType.Image);
                cmd.Parameters["@ImageBinary"].Value = st.ToArray();
                conn.Open();
                try
                {
                    if (cmd.ExecuteNonQuery() > 0)
                    {
                       
                        MessageBox.Show("成功");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
                image.Dispose();
                st.Dispose();
                st.Flush();
                cmd.Clone();
                conn.Close();
               

            }

        }

        private List<int> SelectSet()
        {
            
            string sql = "select ID from Images";
            SqlCommand  com = new SqlCommand(sql,conn);
            conn.Open();
            SqlDataReader data = com.ExecuteReader();
            info = new List<int>();
            while (data.Read())
            {
                info.Add( Int32.Parse( data["ID"].ToString()));
            }
            
            conn.Close();
            com.Clone();
            return info;
        }

        /// <summary>
        /// 从数据库中读耶图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("spSelectImage", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@ImageID", int.Parse(this.comboBox1.Text));
            cmd.Parameters["@ImageID"].Value = Int32.Parse(this.comboBox1.Text);
            
            conn.Open();
            try
            {
                SqlDataReader data = cmd.ExecuteReader();
                if (data.Read())
                {

                    byte[] photo = (byte[])data["Imagee"];
                    MemoryStream ms = new MemoryStream(photo);
                    Image img = Image.FromStream(ms);
                    this.pictureBox1.Image = img;
                    ms.Flush();
                    ms.Close();
                    data.Close();
                }

             
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
            conn.Close();
            cmd.Clone();

        }
这是我写的存图片的应该和你说的那个PDF差不多吧 PDE我真没试过 呵呵  你自己看看吧能否帮到你

#10


先谢了,各位大哥们

#11


引用 7 楼 wdgphc 的回复:
入库:
         C# codeStream ms;byte[] _byte;
            OpenFileDialog ofd=new OpenFileDialog();
            ofd.ShowDialog();string f= ofd.FileName;

            ms= ofd.OpenFile();
            _byte=newbyte[ms.Length];
            ms.Position=0;
            ms.Read(_byte,0, Convert.ToInt32(ms.Length));
            SqlConnection conn=new SqlConnection("server=.;uid=sa;pwd=;database=s");
            conn.Open();string sqlstring="insert into ttt(file) values(@pdf)";
            SqlCommand cmd=new SqlCommand(sqlstring, conn);
            cmd.Parameters.Add("@pdf", SqlDbType.Image, _byte.Length).Value= _byte;


是不是少了一句: cmd.ExecuteNonQuery(); 
现在问题是,保存时,总是提示长度不够,我保存PDF数据类型用的是:varbinary(8000),已经是最大了,怎么办!

#12


先转成byte[] 然后存到image字段中