C#将文件上传、下载(以二进制流保存到数据库)


本文摘自PHP中文网,作者大家讲道理,侵删。

1、将文件以二进制流的格式写入数据库

首先获得文件路径,然后将文件以二进制读出保存在一个二进制数组中,与数据库建立连接,在SQL语句中将二进制数组赋值给相应的参数,完成向数据库中写入文件的操作

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

/// 将文件流写入数据库 

///  

/// <param name="filePath">存入数据库文件的路径 

/// <param name="id">数据库中插入文件的行标示符ID 

/// <returns></returns> 

public int UploadFile(string filePath, string id) 

    byte[] buffer = null

    int result = 0; 

    if (!string.IsNullOrEmpty(filePath)) 

    

        String file = HttpContext.Current.Server.MapPath(filePath);  

        buffer = File.ReadAllBytes(file); 

        using (SqlConnection conn = new SqlConnection(DBOperator.ConnString)) 

        

            using (SqlCommand cmd = conn.CreateCommand()) 

            

                cmd.CommandText = "update DomesticCompanyManage_Main_T set ZBDocumentFile = @fileContents where MainID ='" + id + "'";; 

                cmd.Parameters.AddRange(new[]{ 

                new SqlParameter("@fileContents",buffer) 

            }); 

                conn.Open(); 

                result = cmd.ExecuteNonQuery(); 

                conn.Close(); 

            

        

        return result; 

    

    else

        return 0; 

}

2、从数据库中将文件读出并建立相应格式的文件

从数据库中读取文件,只需根据所需的路径建立相应的文件,然后将数据库中存放的二进制流写入新建的文件就可以了

如果该目录下有同名文件,则会将原文件覆盖掉

1

2

3

4

5

6

7

8

9

10

//从数据库中读取文件流 

//shipmain.Rows[0]["ZBDocument"],文件的完整路径 

//shipmain.Rows[0]["ZBDocumentFile"],数据库中存放的文件流 

if (shipmain.Rows[0]["ZBDocumentFile"] != DBNull.Value) 

    int arraySize = ((byte[])shipmain.Rows[0]["ZBDocumentFile"]).GetUpperBound(0); 

    FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(shipmain.Rows[0]["ZBDocument"].ToString()), FileMode.OpenOrCreate, FileAccess.Write);//由数据库中的数据形成文件 

    fs.Write((byte[])shipmain.Rows[0]["ZBDocumentFile"], 0, arraySize); 

    fs.Close(); 

}

相关阅读 >>

常用的c#类

二叉搜索树插入算法c#

c#中登陆账户使用的md5加密算法

c#分别用前序遍历、中序遍历和后序遍历打印二叉树

c#读取中文文件乱码的解方法

c# 四舍五入round函数使用

c# 识别url是否是网络路径

c#将文件上传、下载(以二进制流保存到数据库)

c#读取host文件代码

c#操作mysql的工具类mysqlhelper

更多相关阅读请进入《代码片段》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...