在云中保存图片

时间:2014-03-15 04:40:19

标签: c# http rest

我正在保存Buddy云上的数据。早些时候我正在保存字符串数据,这很好。现在我必须保存图片,但我得到例外" Bad Request"。实际上,他们指定其类型应为" file"。我不知道如何指定。下面是代码,我必须使用API​​执行此操作。 文档:http://dev.buddyplatform.com/Home/Docs/Create%20Picture/HTTP

        byte[] image = File.ReadAllBytes(imagePath);

        string url = "https://api.buddyplatform.com/pictures";

        // how to specify type below line ? how to correct ?
        string parameters = "{data:'" + image + "'}";

        HttpWebRequest request = null;
        HttpWebResponse response = null;

            request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "application/json";
            request.ContentType = "application/json";
            request.Method = "POST";
            request.Headers.Add("Authorization", "Buddy " + SharedData.buddyTOKEN);

            // send request
            StreamWriter sw = new StreamWriter(await request.GetRequestStreamAsync());
            sw.WriteLine(parameters);
            sw.Close();

            // get response
            response = (HttpWebResponse)await request.GetResponseAsync();

1 个答案:

答案 0 :(得分:0)

您无法通过将字符串与parameters连接来创建请求正文(您的byte[]字符串)。这最终会在ToString()上调用byte[],从而为您留下如下请求:

{ data:'System.Byte[]' }

由于这是作为JSON请求发送的,因此Buddy可能希望使用base64编码文件。这是您在base64中对文件进行编码并将其插入请求的方法:

string parameters = "{data:'" + Convert.ToBase64String(bytes) + "'}";

结果:

{data:'FxgZGurnIBlBCtIAIQ[...rest of your file...]'}