Base64字符串HTTP Post

时间:2014-08-19 01:10:46

标签: c# php ios xamarin http-post

这是我最后两个问题,基本上合并为一个。
我正在使用带有PHP HTTP Post后端的MonoTouch(C#)在Xamarin Studio for iOS中构建应用程序。

在添加允许用户上传自己图像的功能时,我将图像对象转换为Base64字符串以保存为PHP。

过程:
UIImage - > NSData - > byte [] - > Base64字符串 - > HTTP Post - >解码Base64字符串 - > imagecreatefromstring - > imagejpeg以PHP格式保存

这是我在C#中使用的来源

public async void Post (string UID, string imageBase = null)
    {
        string data = "";
        if (imageBase != null) {
            data = string.Format ("METHOD=post&UID={0}&Image={1}", UID, imageBase);
        }

        HttpWebRequest r = await Info.createRequest (data);
        using (var resp = await Task.Factory.FromAsync<WebResponse> (r.BeginGetResponse, r.EndGetResponse, null)) {
            return;
        }
    }

public static async Task<HttpWebRequest> createRequest (string json)
    {
        (new CancellationTokenSource ()).Dispose ();
        var request = WebRequest.Create (BaseUrl) as HttpWebRequest; 
        request.Method = "POST";    
        request.ContentType = "application/x-www-form-urlencoded";

        byte[] postData = Encoding.UTF8.GetBytes (json);
        using (var stream = await Task.Factory.FromAsync<Stream> (request.BeginGetRequestStream, request.EndGetRequestStream, request)) {
            await stream.WriteAsync (postData, 0, postData.Length);
        }

        return request;
    }

这是我在PHP中使用的源代码

imagejpeg(imagecreatefromstring(base64_decode($_POST["Image"], TRUE)), "Users/Images/".$_POST["UID"]."/".md5(uniqid()).".png");

当我从C#代码中获取imageBase字符串并手动将其粘贴到PHP代码中以替换$ _POST [&#34; Image&#34;]时,一切正常。但它目前通过损坏的图像流发送,我只能想象是因为postData是使用UTF8编码的,当它在服务器端解码时,我目前无法处理,它不是解码正确。

我打算尝试使用普通/文本HTTP Post,但这似乎没有任何帮助,因为它更糟糕。

1 个答案:

答案 0 :(得分:0)

通过在baseImage字符串上使用WebUtility.UrlEncode来修复它。