如何将图像base64发送到服务器Windows Phone 8.1

时间:2015-09-28 19:19:27

标签: c# windows-phone-8.1 httprequest

我正在使用c#在Windows Phone 8.1上开发一个应用程序,可以拍照并将其发送到服务器(在base64中),并附带一个帖子请求。

所以我的问题是我找不到一个方法仍可以在我的请求中包含我的图像base64并将其发送到我的服务器。

private async  void validPicture_Click(object sender, RoutedEventArgs e)
    {
        Encode("ms-appx:///xx/xxx.jpg");
        try
        {
            var client = new Windows.Web.Http.HttpClient();
            var uri = new Uri("http://x.x.x.x:x/picture/");
            string pathBase64 = Encode("ms-appx:///xx/xxx.jpg").ToString();

            Dictionary<string, string> pairs = new Dictionary<string, string>();
            pairs.Add("type", "recognition");

            HttpFormUrlEncodedContent formContent = new HttpFormUrlEncodedContent(pairs);
            Windows.Web.Http.HttpResponseMessage response = await client.PostAsync(uri, formContent);

            string content = await response.Content.ReadAsStringAsync();
            if (response.IsSuccessStatusCode)
            {
            }
        }
        catch (Exception eu)
        {

        }
    }

如果您是一个问题或需要更多信息,请告诉我。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

首先,您必须从存储中读取图像文件并将字节转换为base64字符串。

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(PHOTO_PATH));

        byte[] rawBytes;
        using (Stream stream = await file.OpenStreamForReadAsync())
        {
            rawBytes = new byte[stream.Length];
            await stream.ReadAsync(rawBytes, 0, rawBytes.Length);
        }

        string base64Content = Convert.ToBase64String(rawBytes);

然后你必须使用该内容提出请求。我不确定您的服务器如何接受请求,但这里是在内容中使用该字符串发送请求的示例。

var httpClient = new Windows.Web.Http.HttpClient();
        IBuffer content = CryptographicBuffer.ConvertStringToBinary(base64Content, BinaryStringEncoding.Utf8);

        var request = new HttpBufferContent(content);

        HttpResponseMessage response = await httpClient.PostAsync(new Uri(SERVER_URL), request);