c winform 上传文件到mysql_C# winform DevExpress上传图片到数据库【转】

实现功能如下图:

c476495293b1a2296fd4a4743565edd4.png

注明:此文使用的是DevExpress控件,winform 原生控件也是一样使用方法。

1.点击选择图片按钮,功能为通过对话框选择要上传的文件,并将该文件在下面的PictureEdit中显示出来。具体代码如下:

private void btnChoosePic_Click(object sender, EventArgs e)

{

ShowPic(pictureEdit1);

}

///

/// 选择图片

///

///

public static void ShowPic(PictureEdit picEdit)

{

OpenFileDialog ofd = new OpenFileDialog();

ofd.InitialDirectory = @"C:\";

ofd.Filter = "Image Files(*.JPG;*.PNG;*.jpeg;*.GIF;*.BMP)|*.JPG;*.PNG;*.GIF;*.BMP;*.jpeg|All files(*.*)|*.*";

ofd.RestoreDirectory = true;

if (ofd.ShowDialog() == DialogResult.OK)

{

PicAddress = ofd.FileName;

Image imge = Image.FromFile(PicAddress);

Bitmap bm = new Bitmap(imge, picEdit.Width, picEdit.Height);

picEdit.Image = bm;

}

}

ShowPic()方法为静态方法,可以直接调用,其中的PicAddress变量为静态全局变量,用于记录要上传文件的文件地址。PictureEdit显示图片的方式,是通过PictureEdit的image属性设定的,将图片转成Bitmap格式,位图文件是最简单的图片格式。

2.上传图片,该按钮的功能是将选定的图片上传到数据库中,具体的实现代码如下:

///

/// 上传图片

///

///

///

private void btnUploadPic_Click(object sender, EventArgs e)

{

if (PicAddress != null)

{

if (PicType.Equals("教师"))

{

var sqlSearch =

$@"select count(*) from studentmanager.picture where PicTypeId = '{TeacherId}'

and PicType='{PicType}'";

var dsSearch = _db.GetResult(sqlSearch);

if (dsSearch.Tables[0].Rows[0][0].ToString().Equals("0")) //没有重复的,则进行新增插入操作

{

byte[] pic = CommonFunction.GetContent(PicAddress);

var result = _db.SavePictureToDB(pic, PicAddress, PicType, TeacherId);

if (result > 0)

{

CommonFunction.MessageShow("头像添加成功", "提示", "OK", "Information");

DialogResult = DialogResult.OK;

}

else

{

CommonFunction.MessageShow("头像添加失败");

}

}

else

{

//更新头像

if (PicAddress.Equals(String.Empty))

{

CommonFunction.MessageShow("没有重新选择图片进行更新");

return;

}

byte[] pic = CommonFunction.GetContent(PicAddress);

var result = _db.UpdatePictureToDb(pic, PicAddress, PicType, TeacherId);

if (result > 0)

{

CommonFunction.MessageShow("头像更新成功", "提示", "OK", "Information");

DialogResult = DialogResult.OK;

}

else

{

CommonFunction.MessageShow("头像更新失败");

}

}

}

else if(PicType.Equals("学生"))

{

var sqlSearch =

$@"select count(*) from studentmanager.picture where PicTypeId = '{StudentId}'

and PicType='{PicType}'";

var dsSearch = _db.GetResult(sqlSearch);

if (dsSearch.Tables[0].Rows[0][0].ToString().Equals("0")) //没有重复的,则进行新增插入操作

{

byte[] pic = CommonFunction.GetContent(PicAddress);

var result = _db.SavePictureToDB(pic, PicAddress, PicType, StudentId);

if (result > 0)

{

CommonFunction.MessageShow("头像添加成功", "提示", "OK", "Information");

DialogResult = DialogResult.OK;

}

else

{

CommonFunction.MessageShow("头像添加失败");

}

}

else

{

//更新头像

if (PicAddress.Equals(String.Empty))

{

CommonFunction.MessageShow("没有重新选择图片进行更新");

return;

}

byte[] pic = CommonFunction.GetContent(PicAddress);

var result = _db.UpdatePictureToDb(pic, PicAddress, PicType, StudentId);

if (result > 0)

{

CommonFunction.MessageShow("头像更新成功", "提示", "OK", "Information");

DialogResult = DialogResult.OK;

}

else

{

CommonFunction.MessageShow("头像更新失败");

}

}

}

}

else

{

CommonFunction.MessageShow("请先选择图片!", "提示", "OK", "Error");

}

}

上传的过程大概就是:根据文件地址将对应文件转换成数据流二进制格式–>编写对应的SQL语句–>执行该SQL语句,将图片添加到数据库中。

上面代码中SavePictureToDB方法代码如下:

///

/// 保存图片到数据库

///

///

///

///

///

///

///

public int SavePictureToDB(byte[] imageByte,

string Picturename,

string PicType,

int PicTypeId)

{

var result = 0;

try

{

if (imageByte != null && imageByte.Length != 0)

{

using (var conn = new MySqlConnection())

{

conn.ConnectionString = ConnectionString;

conn.Open();

var insertStr = @"INSERT INTO studentmanager.picture

(

Picturename,

PicType,

PicTypeId,

imageByte

)

VALUES

(

@Picturename,

@PicType,

@PicTypeId,

@imageByte

);";

var comm = new MySqlCommand();

comm.Connection = conn;

comm.CommandText = insertStr;

comm.CommandType = CommandType.Text;

//设置数据库字段类型MediumBlob的值为图片字节数组imageByte

comm.Parameters.Add(new MySqlParameter("@imageByte", MySqlDbType.MediumBlob)).Value = imageByte;

comm.Parameters.Add(new MySqlParameter("@Picturename", MySqlDbType.VarChar)).Value = Picturename;

comm.Parameters.Add(new MySqlParameter("@PicType", MySqlDbType.VarChar)).Value = PicType;

comm.Parameters.Add(new MySqlParameter("@PicTypeId", MySqlDbType.Int32)).Value = PicTypeId;

//execute sql

result = comm.ExecuteNonQuery();

comm.Dispose();

conn.Close();

conn.Dispose();

}

}

}

catch (Exception)

{

// throw ex;

}

return result;

}

3.加载图片显示到PictureEdit;

///

/// 窗口加载

///

///

///

private void HeadManager_Load(object sender, EventArgs e)

{

LoadImage(PicType, PicType.Equals("教师") ? TeacherId : StudentId);

}

///

/// 获取图片

///

///

///

private void LoadImage(string picType, int picTypeid)

{

try

{

var imageBytes = _db.GetImage(picType, picTypeid);

var image = CommonFunction.GetImageByBytes(imageBytes);

Bitmap bm = new Bitmap(image, pictureEdit1.Width, pictureEdit1.Height);

pictureEdit1.Image = bm;

}

catch (Exception)

{

pictureEdit1.Image = Resource.DefaultUser;

}

}

4.用到的公共方法:

///

/// 转换为Byte[]

///

///

///

public static byte[] GetContent(string filepath)//将指定路径下的文件转换成二进制代码,用于传输到数据库

{

FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);

byte[] byData = new byte[fs.Length];//新建用于保存文件流的字节数组

fs.Read(byData, 0, byData.Length);//读取文件流

fs.Close();

return byData;

}

///

/// 读取byte[]并转化为图片

///

/// byte[]

/// Image

public static Image GetImageByBytes(byte[] bytes)

{

Image photo;

using (MemoryStream ms = new MemoryStream(bytes))

{

ms.Write(bytes, 0, bytes.Length);

photo = Image.FromStream(ms, true);

ms.Dispose();

ms.Close();

}

return photo;

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/542742.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

V 8 nfs+drbd+heartbeat

V 8 nfsdrbdheartbeatnfsdrbdheartbeat,nfs或分布式存储mfs只要有单点都可用此方案解决在企业实际生产场景中,nfs是中小企业最常用的存储架构解决方案之一,该架构方案部署简单、维护方便,只需通过配inotifyrsync简单而高效的数据同…

nodemailer使用_如何使用Nodemailer使用HTML作为内容发送电子邮件 Node.js

nodemailer使用Prerequisite: 先决条件: How to send emails using Nodemailer | Node.js 如何使用Nodemailer发送电子邮件。 Node.js How to send emails with attachments using Nodemailer | Node.js 如何使用Nodemailer发送带有附件的电子邮件。 Node.js This …

angularjs 元素重复指定次数_[LeetCode] 442. 数组中重复的数据

[LeetCode] 442. 数组中重复的数据题目链接: https://leetcode-cn.com/problems/find-all-duplicates-in-an-array难度:中等通过率:61.5%题目描述:给定一个整数数组 a,其中1 ≤ a[i] ≤ n ( n 为数组长度),…

docker 安装mysql 实战文档_docker 安装mysql

PassJava (佳必过) 项目全套学习教程连载中,关注公众号第一时间获取。docker 安装mysql1.下载镜像sudo docker pull mysql:5.7ubuntuVM-0-13-ubuntu:~$ sudo docker pull mysql:5.75.7: Pulling from library/mysqlc499e6d256d6: Pull complete22c4cdf4ea75: Pull c…

python 补前导零_Python正则表达式| 程序从IP地址中删除前导零

python 补前导零Given an IP address as input, write a Python program to remove leading zeros from it. 给定一个IP地址作为输入,编写一个Python程序以从中删除前导零。 Examples: 例子: Input: 216.08.094.196Output: 216.8.94.196Input: 216.08…

眼球追踪

眼球追踪类似于头部追踪,但是图像的呈现取决于使用者眼睛所看的方向。例如,人们可以用“眼神”完成一种镭射枪的瞄准。眼球追踪技术很受VR专家们密切关注。Oculus创始人帕尔默拉奇就曾称其为“VR的心脏”。对于人眼位置的检测,能够为当前所处…

mysql 创建分区表_Mysql分区表及自动创建分区Partition

Range分区表建表语句如下,其中分区键必须和id构成主键和唯一键CREATE TABLE test1 (id char(32) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT ‘自增主键(guid)‘,create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ‘创建时间‘,partition_key …

python下载文件暂停恢复_Python关于Threading暂停恢复解决办法

我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦start后, 线程就属于失控状态. 不过, 我们可以自己实现这些. 一般的方法就是循环地判断一个标志…

信息系统状态过程图_过程状态图中使用的重要术语| 操作系统

信息系统状态过程图1)上下文切换 (1) Context Switching) Whenever a process is transferred within the system, it moves within different states. These states are known as the process states. When a process goes from one state to another state inside the system…

mysql 吧库下的表名都加_mysql数据库表名大小写问题

mysql数据库表名大小写问题mysql数据库linux版本表名、字段名默认大小写敏感,即区分大小写。查看mysql有关大小写参数:lower_case_file_system是一个只读参数,无法被修改,这个参数是用来告诉你在当前的系统平台(linux\windows等)下…

rgb 灰色_金属+RGB+无线,我要买爆这款海盗船VIRTUOSO鉴赏家游戏耳机

海盗船最近新出的旗舰耳机,VIRTUOSO RGB Wireless SE,中文名叫鉴赏家。耳机一改往日欧美电竞风,改走金属质感高大上简约风,不过讲真,这颜值我吃起来很香。考虑文章过长,我先概括一下入手理由,具…

python 基类 派生类_在Python中具有两个子(派生)类的继承示例

python 基类 派生类In this program, we have a parent class named Details and two child classes named Employee and Doctor, we are inheritance the class Details on the classes Employee and Doctor. And, finally creating two objects of Employee and Doctor class…

连接postgresql

# psycopg2enginecreate_engine(postgresqlpsycopg2://scott:tigerlocalhost/mydatabase)#python 连接postgresql使用psycopg2作为默认的DBAPIThe first time a method like Engine.execute()orEngine.connect()is called, the Engine establishes a real DBAPI connection to …

n的阶乘程序python_Python程序对N阶乘的尾随零进行计数

n的阶乘程序pythonFormula used: 使用的公式: Trailing 0s in N! Count of 5s in prime factors of n! floor(n/5) floor(n/25) floor(n/125) ....Example: 例: Input: N 23Output: 4Factorial of 23 is 25852016738884976640000 which has four …

c mysql使用场景_Mysql 场景

1个SQL题,1个场景题,会有点难度!SQL题该SQL题大量涉及到row_number,case when,group by等高级用法,有一定的实用价值,总结出来,供日后参考Question.1:分组汇总给定筛选条…

以己为壑

2019独角兽企业重金招聘Python工程师标准>>> 今天把软件工程里面关于面向对象的设计学完了,使我对面向对象OOA和OOD的思想有了进一步的认识,各科知识千沟万壑,犬牙交错,的确是这样,能蒙住自己眼的永远是你自己,而不是这个世界,因为美就在那里;裹住自己双足的的永远是…

macos安装vscode_如何使用VSCode进行PostgreSQL开发及调试

Visual Studio Code (VSCode)是一个轻量级但功能强大的源代码编辑器,可在桌面上运行,适用于Windows,macOS和Linux。 它内置了对JavaScript,TypeScript和Node.js的支持,并具有丰富的其他语言(如C,C&#xff…

最小生成树 kruskal_使用Kruskal算法求解Java最小生成树问题

最小生成树 kruskalIn Electronic Circuit we often required less wiring to connect pins together. We can model this wiring problem with a connected, undirected graph G(V, E), where V is the set of pins, E is the set of possible interconnections between pair …

mysql数据库面试题 软件测试_软件测试数据库面试题一

前提本次分享只局限于 sql server 和 mysql 这两种数据库,其他数据库暂不总结正文1. 对查询的字段进行去重(distinct)用法注意:1. distinct【查询字段】,必须放在要查询字段的开头,即放在第一个参数;2. 只能在SELECT 语…

python数码时钟代码_python时钟的实现

from time importsleepimporttimeimportosclassClock(object):"""数字时钟""" def __init__(self, hour0, minute0, second0):"""初始化方法 :param hour: 时 :param minute: 分 :param second: 秒"""self._hourh…