微信摇一摇上传图片素材
作者:互联网
/// <summary> /// 微信摇一摇上传图片素材 图片大小建议120px*120 px,限制不超过200 px *200 px,图片需为正方形。 /// </summary> /// <param name="data">文件流</param> /// <param name="fileName">文件名</param> /// <returns></returns> public async Task<WxBaseResponse<UploadImgResponse>> UploadImg(byte[] data, string fileName) { var accessToken = await GetAccessToken(); var url = $"{wxApi}/shakearound/material/add?access_token={accessToken}"; // 设置参数 string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线 var content = new MultipartFormDataContent(boundary); content.Headers.Remove("Content-Type"); content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary); var contentByte = new ByteArrayContent(data); contentByte.Headers.Remove("Content-Disposition"); contentByte.Headers.TryAddWithoutValidation("Content-Disposition", $"form-data; name=\"media\";filename=\"{fileName}_2.png\"" + ""); contentByte.Headers.Remove("Content-Type"); contentByte.Headers.TryAddWithoutValidation("Content-Type", "image/png"); content.Add(contentByte); return await HttpClientHelper.PostFileAsync<WxBaseResponse<UploadImgResponse>>(url, content); //return await _httpApi.PostAsync<WxBaseResponse<UploadImgResponse>>(url, content); }
public static async Task<T> PostFileAsync<T>(string url, HttpContent content) { using (var httpClient = new HttpClient()) { var uri = new Uri(url); var resp = await httpClient.PostAsync(uri, content); var jsonResult = Encoding.UTF8.GetString(await resp.Content.ReadAsByteArrayAsync()); return JsonConvert.DeserializeObject<T>(jsonResult); } }
api,FormData上传调用:
var count = Request.Form.Files.Count; if (count == 0 || count > 1) { return Ok(ActionResponse.Fail(-1, "没有文件上传或者上传文件数大于1")); } var file = Request.Form.Files[0]; var imgUrl = ""; using (var br = new BinaryReader(file.OpenReadStream())) { byte[] data = br.ReadBytes((int)file.OpenReadStream().Length); var wxResponse = await _wxService.UploadImg(data, file.FileName); if (wxResponse.IsSuccess) imgUrl = wxResponse.Data.PicUrl; else return Ok(ActionResponse.Fail(-1, $"上传文件出错:{wxResponse.Message},错误码:{wxResponse.Code}")); }
标签:content,Headers,微信,await,Content,图片素材,var,摇一摇,contentByte 来源: https://www.cnblogs.com/SmilePastaLi/p/12096289.html