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.pswp.cn/news/542742.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542742.shtml
英文地址,請注明出處:http://en.pswp.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…