如何上传base64格式的图片?

时间:2019-06-21 16:04:37

标签: c#

我正在尝试使用httpclient以base64格式上传图像,有人对此有经验吗?

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var detect = new Dictionary<string, string>
                {
                   { "api_key", API_KEY },
                   { "api_secret", API_SECRET },
                   { "urls", _base64 }
                };

                var content = new FormUrlEncodedContent(detect);
                var response = await client.PostAsync(DETECT_URL, content);

                HttpStatusCode _statusCode = response.StatusCode;

            }

以上代码返回BadRequest,请帮助

非常感谢

1 个答案:

答案 0 :(得分:1)

a,
FormUrlEncodedContentapplication/x-www-form-urlencoded而不是application/json

b,
如果加载了图像,则可以使用以下命令将其转换为base64:

    public string ImageToBase64(Image image)
    {
        using (MemoryStream m = new MemoryStream())
        {
            image.Save(m, image.RawFormat);
            byte[] imageBytes = m.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }