C# ASP.NET Core WebAPI 文件接收 Winform调用WebAPI发送文件

最近做了一个爬虫,把网站的数据爬下来,但是数据需要分发到自己的各个网站,数据中的图片有外链有本站保存的图片,需要将图片文件上传到服务器。

上代码

WebAPI (.net core 3.1)

        [HttpPost]
        public ActionResult PostImage(string imgname)
        {
            //图片保存路径
            var date = DateTime.Now.ToString("yyyyMMdd");
            var path = Path.Combine(imgsavepath, "UploadFile", date);

            string fullName = string.Empty;
            //Request.Form.Files获取客户端POST过来的所有文件
            IFormFileCollection files = Request.Form.Files;
            foreach (FormFile file in files) //遍历处理每一个文件
            {
                //Path.GetExtension()获取文件扩展名
                string exten = Path.GetExtension(file.FileName).ToLower();

                //扩展名不符合要求就不处理
                if (exten != ".jpg" && exten != ".png") continue;

                //Guid.NewGuid().ToString()生成一个GUID风格的文件名避免重名
                //string fileName = Guid.NewGuid().ToString();
                string fileName = file.FileName;

                fullName = Path.Combine(path, fileName);

                //用using语句释放文件资源
                using (FileStream stream = new FileStream(fullName, FileMode.Create, FileAccess.Write))
                {
                    file.CopyTo(stream);
                    stream.Flush();
                }

            }
            return Content("{'result':'ok'}");
        }

Winform (.net framework 4.8.1)

private void button1_Click(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:27154/bbs/PostImage");            //实例化WebRequest对象  
            request.KeepAlive = true;
            request.Date = DateTime.Now;
            request.Accept = "*/*";
            //request.ContentType = "text/html";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            request.Method = "Post";
            request.Headers.Add("Accept-Encoding", "gzip, deflate, br");
            request.ProtocolVersion = HttpVersion.Version10;
            request.Timeout = 30000;

            //using (Stream reqStream = request.GetRequestStream())
            //{
            //    //reqStream.Write(data, 0, data.Length);
            //    //reqStream.Close();
            //}

            var filePath = "D:\\Code\\PostBBS\\bin\\Debug\\NAVER.png";
            //读取file文件
            //FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            //BinaryReader binaryReader = new BinaryReader(fileStream);


            try
            {
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

                int pos = filePath.LastIndexOf("\\");
                string fileName = filePath.Substring(pos + 1);

                //请求头部信息 
                StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));

                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                Stream postStream = request.GetRequestStream();
                postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                postStream.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("文件传输异常: " + ex.Message);
            }
            finally
            {
                //fileStream.Close();
                //binaryReader.Close();
            }


            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            var responsestream = response.GetResponseStream();
            Encoding ec = Encoding.UTF8;
            StreamReader reader = new StreamReader(responsestream, ec);
            var htmlStr = reader.ReadToEnd();
            MessageBox.Show(htmlStr);
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xp_zzp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值