保存 pdf 到数据库时,为什么不能会出现“将截断字符串或二进制数据”。
程序代码:
public partial class Savewendang : Form { private SqlConnection con = null;//数据库连接 private SqlCommand cmd = null;//数据库操作 private BinaryReader read = null;//二进制读取 private long fileSize = 0;//文件大小 private string fileName = null;//文件名字 private string fileType = null;//文件类型 private byte[] files;//文件 SqlBaseClass G_SqlExecute = new SqlBaseClass(); [local]1[/local] GoodsIn f = new GoodsIn(); public Savewendang(GoodsIn f) { this.f = f; InitializeComponent(); } private void Savewendang_Load(object sender, EventArgs e) { } private void selectFileButton_Click(object sender, EventArgs e)//选择文件 { try { //打开对话框 OpenFileDialog dialog = new OpenFileDialog(); if (dialog.ShowDialog() == DialogResult.OK) { fileAddress.Text = dialog.FileName; FileInfo info = new FileInfo(@fileAddress.Text); //获得文件大小 fileSize = info.Length; //提取文件名,三步走 int index = info.FullName.LastIndexOf("."); fileName = info.FullName.Remove(index); fileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1); //获得文件扩展名 fileType = info.Extension.Replace(".", ""); //把文件转换成二进制流 files = new byte[Convert.ToInt32(fileSize)]; FileStream file = new FileStream(fileAddress.Text, FileMode.Open, FileAccess.Read); read = new BinaryReader(file); read.Read(files, 0, Convert.ToInt32(fileSize)); } } catch (Exception ex) { MessageBox.Show("选择文件时候发生了 " + ex.Message); } } private void saveFileButton_Click(object sender, EventArgs e)//保存 { try { con = G_SqlExecute.GetCon(); cmd = con.CreateCommand(); = "insert into tb_wendang (ps_no,fname,wenjian) values (@ps_no,@fname,@files)"; } catch (Exception ex) { MessageBox.Show("连接数据库错误" + ex.Message); } if (fileAddress.Text.Length <= 0) { MessageBox.Show(this, "请选择一个文件", "文件地址不合法", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RtlReading); return; } try { cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@fname", fileName); cmd.Parameters.AddWithValue("@files", files); cmd.Parameters.AddWithValue("@ps_no", PropertyClass.GetGoodsID); if (fileSize > 0) { string[] type = { "pdf" }; bool exists = ((IList)type).Contains(fileType.ToLower()); if (!exists) { MessageBox.Show("文档格式不对!只能为pdf格式。", "提示对话框", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } } string strsql = "select * from tb_wendang where ps_no='" + PropertyClass.GetGoodsID + "' and fname='" + fileName + "'"; SqlDataReader u = G_SqlExecute.GetReader(strsql); u.Read(); if (u.HasRows) { MessageBox.Show(" 已存在名为" + fileName + "的文档"); return; } if (cmd.ExecuteNonQuery() > 0) { MessageBox.Show(fileName + " 保存成功!"); } else { MessageBox.Show("发生错误!!"); } } catch (Exception ex) { MessageBox.Show("保存 " + fileName + " 时候发生了 " + ex.Message); } } } }
[ 本帖最后由 落叶飘香 于 2014-8-2 08:54 编辑 ]