【c#】winform 上传图片

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).aspx
2.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);
                    }
                }
            }
        }

 

转载于:https://www.cnblogs.com/miskis/p/7607024.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是C# WinForm上传文件的示例代码: ```csharp private void btnUpload_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; string url = "http://localhost/UploadFileWeb/WebForm1.aspx"; string paramName = "file"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); request.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string header = string.Format(headerTemplate, paramName, Path.GetFileName(filePath)); byte[] headerBytes = Encoding.UTF8.GetBytes(header); requestStream.Write(headerBytes, 0, headerBytes.Length); using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } } byte[] trailerBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailerBytes, 0, trailerBytes.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string responseText = reader.ReadToEnd(); MessageBox.Show(responseText); } } } } ``` 该示例代码使用HttpWebRequest类向指定的URL上传文件。在上传文件之前,需要设置请求的Method为POST,ContentType为multipart/form-data,并设置请求头部的边界(boundary)。然后,将文件内容写入请求流中,最后发送请求并获取响应。在获取响应后,可以从响应流中读取服务器返回的内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值