標籤:並儲存 dialog ati move gen 尾碼 添加 zh-cn agent
1、拖拽上傳圖片1.1、後台代碼中修改表單內容,添加 AllowDrop = true
1.2、給表單添加拖拽事件,在事件列表找到拖拽 雙擊即可:
在 DragDrop 產生的方法中添加代碼如下:
private void Form1_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Move; } else { e.Effect = DragDropEffects.None; } }
在 DragEnter 方法中添加代碼如下:
private void Form1_DragEnter(object sender, DragEventArgs e) { //判斷 string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; string file = files[0]; if (!file.ToLower().EndsWith(".png") && !file.ToLower().EndsWith(".jpg")) { MessageBox.Show("需要圖片檔案!"); return; } //PictureBox控制項顯示圖片 Image.Load(file); }2、點擊按鈕上傳圖片2.1、官方文檔地址:https://msdn.microsoft.com/zh-cn/library/system.windows.controls.openfiledialog.filter(v=VS.95).aspx2.2、在表單中添加控制項 OpenFileDialog ,提供了提示使用者開啟檔案的功能。按鈕添加代碼如下:
private void button1_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { //PictureBox控制項顯示圖片 Image.Load(openFileDialog.FileName); } }2.3、上傳圖片並儲存
private void button1_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { //PictureBox控制項顯示圖片 Image.Load(openFileDialog.FileName); //擷取使用者選擇檔案的尾碼名 string extension = Path.GetExtension(openFileDialog.FileName); //聲明允許的尾碼名 string[] str = new string[] { ".gif", ".jpge", ".jpg", ".png" }; if (!str.Contains(extension)) { MessageBox.Show("僅能上傳gif,jpge,jpg格式的圖片!"); } else { //擷取使用者選擇的檔案,並判斷檔案大小不能超過20K,fileInfo.Length是以位元組為單位的 FileInfo fileInfo = new FileInfo(openFileDialog.FileName); if (fileInfo.Length > 20480) { MessageBox.Show("上傳的圖片不能大於20K"); } else { //絕對路徑 string image = openFileDialog.FileName; // 是指XXX.jpg string picpath = openFileDialog.SafeFileName; File.Copy(openFileDialog.FileName, Application.StartupPath + "\\Image\\" + picpath); } } } }
【c#】winform 上傳圖片