C#将文件上传、下载(以二进制流保存到数据库)
发布时间:2020-12-15 17:53:31 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 /// 将文件流写入数据库 /// /summary /// param name="filePath"存入数据库文件的路径/param /// param name="id"数据库中插入文件的行标示符ID/para
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 /// 将文件流写入数据库 /// </summary> /// <param name="filePath">存入数据库文件的路径</param> /// <param name="id">数据库中插入文件的行标示符ID</param> /// <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、从数据库中将文件读出并建立相应格式的文件 //从数据库中读取文件流 //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"],arraySize); fs.Close(); } 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |