Winform+.Net6实现图片拖拽上传

845a034c0758c64039c530dbf2c6699a.png

前言

da48e68040a6872340926a42b2a2b0aa.png

269ea8cf6400e71894deab97cd4016b5.png

    如题,跟你使用过的某些拖拽上传的网站或者Web框架一样,将图片拖拽到指定位置后直接进行上传以及预览,减少找文件、操作的时间。本文主要使用WinformPictureBox控件+.Net6 WebApi实现。

5ca913a3d98aa900efacd5f19cd0cb15.png

3d3c7efcb9dc173f5274336cca62014f.gif

d14c61e0d76b40f55c3e252976c1c231.jpeg

开发环境:.NET Framework4.8+.Net6

开发工具:Visual Studio 2022

ff3b1b994d4dfada18c5a91e5dc5ce69.png

实现步骤

c2619c457b97e5261bd12e32189e291a.png

  1. 创建自定义控件,继承自PictureBox,然后定义以下属性

    private string _NullDesc;
            [Description("没有图像时的描述")]
            public string NullDesc { get { return _NullDesc; } set { _NullDesc = value; Invalidate(); } }
    
    
            private Font _NullDescFont;
            [Description("没有图像时的描述字体")]
            public Font NullDescFont { get { return _NullDescFont; } set { _NullDescFont = value; Invalidate(); } }
    
    
    
    
            private Color _NullDescFontColor;
            [Description("没有图像时的描述字体颜色")]
            public Color NullDescFontColor { get { return _NullDescFontColor; } set { _NullDescFontColor = value; Invalidate(); } }
    
    
            [Description("上传事件")]
            public event EventHandler Upload;
            public new Image Image
            {
                get
                {
                    return base.Image;
                }
                set
                {
                    base.Image = value;
                    if (value != null)
                    {
                        Upload?.Invoke(this, new EventArgs());
                    }
                   
                }
            }
  2. 处理拖拽事件

protected override void OnDragEnter(DragEventArgs drgevent)
        {
            base.OnDragEnter(drgevent);
            if (drgevent.Data.GetDataPresent(DataFormats.FileDrop) || drgevent.Data.GetDataPresent(DataFormats.Bitmap))
            {
                drgevent.Effect = DragDropEffects.Copy;
            }
            else
            {
                drgevent.Effect = DragDropEffects.None;
            }
        }


        protected override void OnDragDrop(DragEventArgs drgevent)
        {
            base.OnDragDrop(drgevent);
            Image = GetImage(drgevent.Data);
        }
  1. 重写OnPaint事件,做以下处理

    protected override void OnPaint(PaintEventArgs e)
            {
                base.OnPaint(e);
                Graphics g = e.Graphics;
                if (Image == null && BackgroundImage == null && !string.IsNullOrWhiteSpace(NullDesc))
                {
                    SizeF sf = g.MeasureString(NullDesc, NullDescFont, Size);
                    float x = (Width - sf.Width) / 2;
                    float y = (Height - sf.Height) / 2;
                    g.DrawString(NullDesc, Font, new SolidBrush(NullDescFontColor), new PointF(x, y));
                }
               
            }
  1. Upload事件中完成上传

private async void PictureBoxEx1_Upload(object sender, EventArgs e)
        {
            HttpClient client = new HttpClient();


            MemoryStream memoryStream = new MemoryStream();
            Image img = (Image)pictureBoxEx1.Image.Clone();
            img.Save(memoryStream, img.RawFormat);
            memoryStream.Seek(0, SeekOrigin.Begin);


            MultipartFormDataContent content = new MultipartFormDataContent();
            StreamContent streamContent = new StreamContent(memoryStream);
            streamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
            {
                Name = "file",
                FileName = "upload" + GetExtension(img)
            };
            content.Add(streamContent);
            var result =await client.PostAsync("https://localhost:7075/Default/Upload", content);
            MessageBox.Show(await result.Content.ReadAsStringAsync());
        }
  1. 后台接收文件

public string Upload(IFormFile file)
        {
            string basePath = AppContext.BaseDirectory + "upload\\";
            if (file == null || file.Length == 0)
            {
                return "文件不可为空";
            }
            if (!Directory.Exists(basePath))
            {
                Directory.CreateDirectory(basePath);
            }
            string filter = Path.GetExtension(file.FileName);
            string fileName = DateTime.Now.Ticks + filter;
            string savePath = basePath + fileName;
            using var stream = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            file.CopyTo(stream);
            return "上传成功";
        }

4dd43608b3e9901e9e9b5e3475af3ef2.png

实现效果

abcd72914c1a432bb678786926759d6f.png

9eac4cff4284cd7c73d52c6939babba0.gif

-技术群:添加小编微信并备注进群
小编微信:mm1552923   公众号:dotNet编程大全
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值