通过WEB服务将任意文件保存到SQL

在数据库上创建一个字段,名为File_F,数据类型为Image

Web 服务
//保存文件
[WebMethod]
public string saveFile(byte[] bytes)
{
            string strProvider = "Data Source=datasouce;"
                            + "Initial Catalog=database;"
                            + "User ID=sa;"
                            + "PassWord=";
            SqlConnection Conn = new SqlConnection(strProvider);
            Conn.Open();
            string strSqlse1 = "Insert Into FileTable(File_F)"
                            + "Values(@file)";
            SqlCommand cmd = new SqlCommand(strSqlse1 , Conn);
            //Create parameter for insert command and add to SqlCommand object.
            SqlParameter prm = new SqlParameter("@file", SqlDbType.VarBinary, bytes.Length,    ParameterDirection.Input, false,
                        0, 0, null, DataRowVersion.Current, bytes);
            cmd.Parameters.Add(prm);

            //Open connection, execute query, and close connection.
           
            cmd.ExecuteNonQuery();
            Conn.Close();


            return "OK";
 }

//读文件
[WebMethod]
public byte[] readFile()
{
            SqlDataReader dr = null;
            string strProvider = "Data Source=datasource;"
                               + "Initial Catalog=database;"
                               + "User ID=sa;"
                               + "PassWord=password";
            SqlConnection Conn = new SqlConnection(strProvider);
            Conn.Open();
            SqlCommand cm = new SqlCommand();
            cm.Connection = Conn;
            cm.CommandType = CommandType.Text;
            cm.CommandText = "select File_F from FileTable";
            dr = cm.ExecuteReader();
          
            byte[] File = null;
            if (dr.Read())
            {
                File = (byte[])dr[0];
            }
            Conn.Close();
            return File;
}

客户端,将文件转为文件流
FileStream fsBLOBFile = new FileStream(strBLOBFilePath, FileMode.Open, FileAccess.Read);
Byte[] bytBLOBData = new Byte[fsBLOBFile.Length];
fsBLOBFile.Read(bytBLOBData, 0, bytBLOBData.Length);
fsBLOBFile.Close();

将文件流转为文件(f1为返回的byte[])
string strTga = saveFileDialog1.FileName;
FileStream fs;
FileInfo fi = new System.IO.FileInfo(strTga);
fs = fi.OpenWrite();
fs.Write(f1, 0, f1.Length);
fs.Close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值