【c#】winform 上傳圖片

一、拖拽上傳圖片

1.一、後臺代碼中修改窗體屬性,添加 AllowDrop = true 

1.二、給窗體添加拖拽事件,在事件列表找到拖拽 雙擊便可:

DragDrop 生成的方法中添加代碼以下:windows

 private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

在 DragEnter 方法中添加代碼以下: spa

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.一、官方文檔地址:https://msdn.microsoft.com/zh-cn/library/system.windows.controls.openfiledialog.filter(v=VS.95).aspx
2.二、在窗體中添加控件 OpenFileDialog ,提供了提示用戶打開文件的功能。按鈕添加代碼以下:
 private void button1_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //PictureBox控件顯示圖片
                Image.Load(openFileDialog.FileName);
            }
        }
2.三、上傳圖片並保存
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);
                    }
                }
            }
        }
相關文章
相關標籤/搜索