C#端
public static string HttpUploadFile(string url, string[] files, Dictionary<string, string> data, Encoding encoding)
{
string boundary = DateTime.Now.Ticks.ToString("X");
byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endbytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
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())
{
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);
}
}
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))
{
byte[] fileContentByte = new byte[fileStream.Length];
fileStream.Read(fileContentByte, 0, Convert.ToInt32(fileStream.Length));
stream.Write(fileContentByte, 0, fileContentByte.Length);
}
}
stream.Write(endbytes, 0, endbytes.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string result = stream.ReadToEnd();
return result;
}
}
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);
}
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)