当前位置:   article > 正文

C#上传多图像文件到Flask_c# 多图片上传

c# 多图片上传

C#端

        public static string HttpUploadFile(string url, string[] files, Dictionary<string, string> data, Encoding encoding)
        {
            //必须
            string boundary = DateTime.Now.Ticks.ToString("X");
            //必须的

            //form 开始标志
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            //form 结尾标志
            byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");

            //1.HttpWebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;
            request.Credentials = CredentialCache.DefaultCredentials;

            using (Stream stream = request.GetRequestStream())
            {
                //传递参数模板 Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}
                //1.1 key/value
                string formdataTemplate = "Content-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}";
                //传递参数
                if (data != null)
                {
                    foreach (string key in data.Keys)
                    {
                        //传递参数开始标识
                        stream.Write(boundarybytes, 0, boundarybytes.Length);

                        string formitem = string.Format(formdataTemplate, key, data[key]);

                        byte[] formitembytes = encoding.GetBytes(formitem);

                        stream.Write(formitembytes, 0, formitembytes.Length);
                    }
                }

                //上传文件模板
                //1.2 file
                string headerTemplate = "Content-Disposition:form-data;name=\"{0}\";filename=\"{1}\"\r\nContent-Type:application/octet-stream\r\n\r\n";

                for (int i = 0; i < files.Length; i++)
                {
                    //上传文件标识
                    stream.Write(boundarybytes, 0, boundarybytes.Length);

                    string header = string.Format(headerTemplate, "file" + i, Path.GetFileName(files[i]));

                    byte[] headerbytes = encoding.GetBytes(header);

                    stream.Write(headerbytes, 0, headerbytes.Length);


                    //将文件流读入到请求流中
                    using (FileStream fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
                    {
                        //int r = fileStream.Read(buffer, 0, buffer.Length);
                        //stream.Write(buffer, 0, r);
                        byte[] fileContentByte = new byte[fileStream.Length];
                        fileStream.Read(fileContentByte, 0, Convert.ToInt32(fileStream.Length));
                        //fileStream.Close();

                        stream.Write(fileContentByte, 0, fileContentByte.Length);

                    }
                }

                //form 结束标志
                //1.3 form end
                stream.Write(endbytes, 0, endbytes.Length);
            }
            //2.WebResponse
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {

                string result = stream.ReadToEnd();
                return result;
            }
        }


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
            try
            {
                for (int i = 0; i < 999999999999; i++)
                {
                    string apiUrl = textBox1.Text.Trim();
                    string imgPath = textBox2.Text.Trim();

                    string[] imgsPath = { imgPath , imgPath , imgPath , imgPath , imgPath , imgPath , imgPath };

                    Dictionary<string, string> send_params = new Dictionary<string, string>();
                    send_params["algoId"] = "1";

                    ServiceAPI.HttpUploadFile(apiUrl, imgsPath, send_params, Encoding.UTF8);
                    Thread.Sleep(2);
                }

            }
            catch(Exception exp) {
                MessageBox.Show(exp.Message);
            
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Flask端

from flask import Flask, request,url_for,render_template
import numpy as np
import cv2
import io
import datetime
from PIL import Image
import logging
from waitress import serve

'''
单项目日志系列配置
'''


logging.basicConfig(

    filename= "test.log",  # 日志记录文件位置
    format= '%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(message)s', # 时间-项目名称-信息等级-信息所属模块-信息
    datefmt= '%Y-%m-%d %H:%M:%S', # 时间记录的格式
    level=0,  #  阈值,超过该阈值的程度信息才会被记录到文本日志文件中。  调试一把设置为0,生产运行时一般是40
)


# flask实例
app = Flask(__name__)

@app.route("/predict",methods=['GET','POST'])
def predict():
    # global v8Model
    startTime = datetime.datetime.now()
    fileList = request.files
    endTime = datetime.datetime.now()
    durTime = '接受数据时间:%dms' % (
                (endTime - startTime).seconds * 1000 + (endTime - startTime).microseconds / 1000)
    print(durTime)
    logging.info(durTime)
    # fileList['file0'].save('file0.jpg')
    # fileList['file1'].save('file1.jpg')
    startTime = datetime.datetime.now()

    image = Image.open(fileList['file0'])


    endTime = datetime.datetime.now()
    durTime = '转opencv numpy时间:%dms' % (
                (endTime - startTime).seconds * 1000 + (endTime - startTime).microseconds / 1000)
    print(durTime)
    logging.info(durTime)



    return "OK"


if __name__ == '__main__':
    # flask
    # app.run(host='127.0.0.1', port=6000)

    # flask+waitress
    serve(app, host='127.0.0.1', port=6000)




  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号