using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ShenTun.ImageCollection.Common { public class ApiService { private readonly HttpClient _httpClient; public ApiService() { _httpClient = new HttpClient(); } public async Task PostAsync(string url, string token, object data) { _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); var jsonStr=Newtonsoft.Json.JsonConvert.SerializeObject(data); var content = new StringContent(jsonStr, Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(url, content); var responseContent = await response.Content.ReadAsStringAsync(); return responseContent; } public string GetUploadApi(string website) { Uri uri = new Uri(website); Uri uri2 = new Uri(uri, "api/app/RegisterCheckPicture/UpdateRegisterCheckPicture"); return uri2.ToString(); } public async Task UploadImage(MemoryStream stream,SelectImageInfo imageInfo) { int iPosS=imageInfo.Image.localPathName.LastIndexOf("."); int iPos = imageInfo.Image.localPathName.LastIndexOf("\\"); string localFilename = imageInfo.Image.localPathName.Substring(iPos + 1, iPosS-iPos-1); byte[] imageBytes = stream.ToArray(); PictureBaseStr baseStr = new PictureBaseStr() { registerCheckPictureId = imageInfo.Image.id, localPathName = imageInfo.Image.localPathName, fileName = localFilename, pictureBaseStr = Convert.ToBase64String(imageBytes) }; string url = GetUploadApi(imageInfo.ImageSvr); var resStr = await PostAsync(url, imageInfo.Token, baseStr); if(resStr.Contains("")) { MessageBox.Show("Token验证没通过"); return; } DialogResponse res=JsonHelper.DeserializeObject(resStr); if (res.code >=0) { MessageBox.Show(string.Format("文件:{0}上传成功!", localFilename)); } else { MessageBox.Show(string.Format("文件:{0}上传失败:{1}", localFilename,res.message)); } } } }