winform端上傳圖片至flask伺服器
阿新 • • 發佈:2018-11-11
winform端程式碼:
public static string PostImageData(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies) { System.GC.Collect();//垃圾回收,回收沒有正常關閉的http連線 string result = ""; HttpWebRequest request = null; HttpWebResponse response = null; //如果是傳送HTTPS請求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { request = WebRequest.Create(url) as HttpWebRequest; } else { // request = WebRequest.Create(url) as HttpWebRequest; request = (HttpWebRequest)WebRequest.Create(url); } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //request.ContentLength = data.Length; //設定代理UserAgent和超時 //request.UserAgent = userAgent; //request.Timeout = timeout; if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //傳送POST資料 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); i++; } } byte[] data = Encoding.ASCII.GetBytes(buffer.ToString()); request.ContentLength = data.Length; using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); stream.Close(); } //獲取服務端返回 response = (HttpWebResponse)request.GetResponse(); //獲取服務端返回資料 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); result = sr.ReadToEnd().Trim(); sr.Close(); } string[] values = request.Headers.GetValues("Content-Type"); return result; }
string url = "http://127.0.0.1:5000/upload"; IDictionary<string, string> parameters = new Dictionary<string, string>(); byte[] byteData = GetPictureData(m_filepath); string picStr = Convert.ToBase64String(byteData); parameters.Add("picStr", picStr); string mes = HttpService.PostImageData(url, parameters, 3000, null, null); label_message.Text = mes;
flask端程式碼:
@app.route('/upload', methods=['POST']) def upload(): #upload_file = request.files["picture"] # imgdata = base64.b64decode(upload_file) # file = open('1.jpg', 'wb') # file.write(imgdata) # file.close() upload_file = request.form.get("picStr") upload_file = urllib.parse.quote_plus(upload_file, safe="/=") # upload_file = bytes(upload_file, encoding="utf8") imgdata = base64.b64decode(upload_file) print(len(imgdata)) global savePath savePath = os.getcwd() + "/upload/" + str(uuid.uuid1()) + ".jpg" print(savePath) file = open(savePath, 'wb') file.write(imgdata) file.close() # img_array = np.fromstring(imgdata, np.uint8) # 轉換np序列 # img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB) # 轉換Opencv格式 #cv2.imwrite('4.jpg', img) return "圖片上傳成功!"