C#客户端上传多张照片+若干参数到服务端

2 篇文章 0 订阅

客户端通过API方式上传多张照片与若干参数到服务器的操作:(示例以两张照片)

客户端代码如下:

客户端辅助类:——作用是将上传参数拼接到URL中,以便服务端获取

public class Utils
    {
        public static string BuildQuery(Dictionary<string, string> dir) {
            string data = null;
            string itemValue = null;
            for (int i = 0; i < dir.Count; i++)
            {
                
                var item = dir.ElementAt(i);//获取字典的下标为i的<key,value>值
                var itemKey = item.Key;  //获取上面得到的key值
                if (i < (dir.Count - 1))
                {
                    itemValue = item.Value + "&";//获取上面得到的value值
                }
                else {
                    itemValue = item.Value;
                }
                data += itemKey + "=" + itemValue;
            }
            return data;
        }
    }

客户端上传方法

方法一访问两次服务端的api

public void UploadImage(string imgPath, string imgPath2)
        {
            var uploadUrl = "http://localhost:6943/IPC/UpdateVisionInspection";
            FileStream fs2 = new FileStream(imgPath2, FileMode.Open, FileAccess.Read);
            byte[] bArr2 = new byte[fs2.Length];
            fs2.Read(bArr2, 0, bArr2.Length);
            fs2.Close();

            FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
            byte[] bArr = new byte[fs.Length];
            fs.Read(bArr, 0, bArr.Length);
            fs.Close();
            int pos = imgPath.LastIndexOf("\\");
            string fileName = imgPath.Substring(pos + 1);

            int pos2 = imgPath2.LastIndexOf("\\");
            string fileName2 = imgPath.Substring(pos2 + 1);
            var dic = new Dictionary<string, string>() {
                {"param1","*****"},
                {"param2", "******"},
                {"param3", "******" },
                {"StandardFileName",fileName },
                {"DetectedFileName", fileName2},
                {"StandardFileLength", bArr.Length.ToString() },
                {"DetectedFileLength", bArr2.Length.ToString() }
                };
            var postData = Utils.BuildQuery(dic);//转换成:para1=1&para2=2&para3=3&...
            var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
            HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
            request.AllowAutoRedirect = true;
            request.Method = "POST";

            

            byte[] bArrSum = new byte[bArr.Length + bArr2.Length];
            bArr.CopyTo(bArrSum, 0);
            bArr2.CopyTo(bArrSum, bArr.Length);

            Stream postStream = request.GetRequestStream();
            postStream.Write(bArrSum, 0, bArrSum.Length);
            postStream.Close();

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();

        }

方法二:访问一次服务端的api

public void UploadImage(List<string> files)

{

            var uploadUrl = "http://localhost:6943/IPC/UpdateVisionInspection";
            int count = 1;
            foreach (string imgPath in files)
            {

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

                var dic = new Dictionary<string, string>() {
                {"param1","*****"},
                {"param2", "******"},
                {"param3", "******" },
                {"StandardFileName",fileName },
                {"DetectedFileName", fileName2},
                {"StandardFileLength", bArr.Length.ToString() },
                {"DetectedFileLength", bArr2.Length.ToString() }
                };
                var postData = Utils.BuildQuery(dic);//转换成:para1=1&para2=2&para3=3
                var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
                FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
                byte[] bArr = new byte[fs.Length];
                fs.Read(bArr, 0, bArr.Length);
                fs.Close();

                HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
                request.ContentType = "image/jpeg";
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                Encoding encoding = Encoding.UTF8;
                Stream postStream = request.GetRequestStream();
                postStream.Write(bArr, 0, bArr.Length);
                postStream.Close();

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream instream = response.GetResponseStream();
                StreamReader sr = new StreamReader(instream, Encoding.UTF8);
                string content = sr.ReadToEnd();

                Console.WriteLine((count++) + "/" + files.Count);
            }

服务端接收方法:图片将会保存到D:\\AtestImage\\param1文件中,本例保存两张图片,一张为param1+"Detected.bmp",另一张为param2+"Standard.bmp",如下图所示:图中的433即为客户端上传的param1

                                                       

public JsonResult UpdateVisionInspection(string param1, string param2, string param3, string StandardFileName, string DetectedFileName, string StandardFileLength, string DetectedFileLength)
        {

            string rootPath = "D:\\AtestImage\\" + param1 + "\\";//图片保存路径设置
            if (!Directory.Exists(rootPath))
            {
                Directory.CreateDirectory(rootPath);
            }
            System.IO.Stream stream = Request.InputStream;
            byte[] bytes = new byte[stream.Length + 1]//+1真的很重要
            stream.Read(bytes, 0, bytes.Length);
            //设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            //将bytes转换为流
            Stream newStream = new MemoryStream(bytes);
            stream.Close();
            stream.Dispose();

            byte[] standarBuffer = new byte[Convert.ToInt32(StandardFileLength)];
            byte[] detectedBuffer = new byte[Convert.ToInt32(DetectedFileLength)];
            int streamLength = Convert.ToInt32(stream.Length);
            try
            {
                using (FileStream standardFS = new FileStream(rootPath + param1 + "Standard" + ".bmp", FileMode.Create))
                {
                    while ((newStream.Read(standarBuffer, 0, Convert.ToInt32(StandardFileLength))) > 0)
                    {
                        standardFS.Write(standarBuffer, 0, Convert.ToInt32(StandardFileLength));
                    }
                };
                newStream.Seek(Convert.ToInt32(StandardFileLength), SeekOrigin.Begin);
                using (FileStream detectedFS = new FileStream(rootPath + param1 + "Detected" + ".bmp", FileMode.Create))
                {
                    while ((newStream.Read(detectedBuffer, 0, Convert.ToInt32(DetectedFileLength))) > 0)
                    {
                        detectedFS.Write(detectedBuffer, 0, Convert.ToInt32(DetectedFileLength));
                    }
                };

            }
            catch (IOException ioe)
            {
                Response.Write(ioe);
            }
            newStream.Flush();
            newStream.Close();
            newStream.Dispose();

            return new JsonResult { };
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值