将文档文件插入SQL Server中的列中

本文关键字:Server SQL 文档 文件 插入 | 更新日期: 2023-09-27 18:25:12

我想在SQL Server的字段中保存一个文档文件。该文档文件可以包含文本、图表、表格和图片。

我想把这个文件保存在一个字段中,只要我愿意,我就可以在这些文档文件中搜索并找到我的搜索标题。

我该怎么做?

将文档文件插入SQL Server中的列中

在表中创建一列数据类型为varbinary(max)的列,然后尝试-

string filePath = FileUpload1.PostedFile.FileName;  
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
 switch(ext)
{
    case ".doc":
        contenttype = "application/vnd.ms-word";
        break;
    case ".docx":
        contenttype = "application/vnd.ms-word";
        break;
}
 if (contenttype != String.Empty)
{
    Stream fs = FileUpload1.PostedFile.InputStream;
    BinaryReader br = new BinaryReader(fs);
    Byte[] bytes = br.ReadBytes((Int32)fs.Length);
    //insert the file into database
    string strQuery = "insert into tblFiles(Name, ContentType, Data)" +
       " values (@Name, @ContentType, @Data)";
    SqlCommand cmd = new SqlCommand(strQuery);
    cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
    cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value
      = contenttype;
    cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
    InsertUpdateData(cmd);
    lblMessage.ForeColor = System.Drawing.Color.Green;  
    lblMessage.Text = "File Uploaded Successfully";
}

您可以在SQL中创建一个类型为VARBINARY(MAX)的新数据库字段,该字段可以保存任何数据。为了将Doc文件保存到其中,我将用一个例子来帮助您。

        // Read the file and convert it to Byte Array
        string filePath = FileUpload1.PostedFile.FileName;  
        string filename = Path.GetFileName(filePath);
        Stream fs = FileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);

        //insert the file into database
        string strQuery = "insert into tblFiles(Name, Data)" +
           " values (@Name, @Data)";
        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;

        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
        InsertUpdateData(cmd);
        lblMessage.ForeColor = System.Drawing.Color.Green;  
        lblMessage.Text = "File Uploaded Successfully";

这里字段CCD_ 3在SQL中被定义为CCD_。

对于您的第二个要求,要在DOC中搜索文本,请参阅配置和管理搜索的过滤器

谢谢我的朋友但我希望能够在我的文档中进行搜索。文档文件可以包含表格,表格可以包含任何类型的数据,如文本、数字和
图表和图片也可以像表格一样
我不想在字段中保存我的文档的路径,任何时候我都需要先搜索,然后打开文件再搜索
我想将该文档文件保存到一个字段中,并在字段

上搜索