尝试将ImageData发送到我的数据库

时间:2016-02-04 18:32:59

标签: c# image xamarin xamarin.forms

我正在尝试将imagedata发送到我的数据库,但我不确定应该如何让它工作。这是我目前的代码:

这是我的数据库csfile,我尝试在我的数据库中创建一个图像(它正在工作,但我不确定是否应该将其作为byte []发送,因为我的数据库想要它作为文件)

static public async Task<bool> createInfo (byte[] thePicture) // should I send it as byte??

我“创建”我发送到数据库csfile的数据的页面。

myViewModel = new PhotoAlbumViewModel ();

async void button (object sender, EventArgs args)
    { 
        var createResult = await parseAPI.createInfo 
            (myViewModel.ImageData); //sending my imagedata to my database
    }

我的PhotoAlbumViewModel,我在其中创建包含带有imagedata的字节的ImageData:

    private byte[] imageData;

    public byte[] ImageData { get { return imageData; } }

    private byte[] ReadStream(Stream input)
    {
        byte[] buffer = new byte[16*1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

public async Task SelectPicture()
    {
        Setup ();

        ImageSource = null;


        try
        {
            var mediaFile = await _Mediapicker.SelectPhotoAsync(new CameraMediaStorageOptions
                {
                    DefaultCamera = CameraDevice.Front,
                    MaxPixelDimension = 400
                });

            VideoInfo = mediaFile.Path;
            ImageSource = ImageSource.FromStream(() => mediaFile.Source);

            imageData = ReadStream(mediaFile.Source);


        }
        catch (System.Exception ex)
        {
            Status = ex.Message;
        }
    }

更新了数据库cscode:

static public async Task<bool> createInfo (byte[] thePicture)

    {
        var httpClientRequest = new HttpClient ();

        httpClientRequest.DefaultRequestHeaders.Add ("X-Parse-Application-Id", appId);
        httpClientRequest.DefaultRequestHeaders.Add ("X-Parse-REST-API-Key", apiKey);

        var postData = new Dictionary <object, object> ();
        postData.Add ("image", thePicture);

        var jsonRequest = JsonConvert.SerializeObject(postData);

        jsonRequest = jsonRequest.Replace ("\"ACLDATA\"", "{\""+userId+"\" : { \"read\": true, \"write\": true }, \"*\" : {}}");

        HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");

        var result = await httpClientRequest.PostAsync("https://api.parse.com/1/classes/Info", content);
        var resultString = await result.Content.ReadAsStringAsync ();

        return  true;
    }

1 个答案:

答案 0 :(得分:1)

最后,您遇到的问题是您的Post API调用错误。

它期望一个普通的POST请求,其内容为二进制,并且您正在执行REST请求。

此代码可以执行此操作:

    public static void SendFile(string FileName, string MimeType, byte[] FileContent, string ClientId, string ApplicationId, string ApiKey, Action<string> OnCompleted)
    { 
        string BaseServer =   "https://api.parse.com/{0}/files/{1}";

        HttpWebRequest req = HttpWebRequest.CreateHttp(string.Format(BaseServer, ClientId, FileName));

        SetHeader(req, "X-Parse-Application-Id", ApplicationId);
        SetHeader(req, "X-Parse-REST-API-Key", ApiKey);

        req.Method = "POST";
        req.ContentType = MimeType;

        req.BeginGetRequestStream((iResult) =>
            {
                var str = req.EndGetRequestStream(iResult);
                str.Write(FileContent, 0, FileContent.Length);

                req.BeginGetResponse((iiResult) => {

                    var resp = req.EndGetResponse(iiResult);

                    string result = "";

                    using (var sr = new StreamReader(resp.GetResponseStream()))
                        result = sr.ReadToEnd();

                    OnCompleted(result);

                }, null);


            }, null);

    }

    //Modified from http://stackoverflow.com/questions/14534081/pcl-httpwebrequest-user-agent-on-wpf
    public static void SetHeader(HttpWebRequest Request, string Header, string Value) {
        // Retrieve the property through reflection.
        PropertyInfo PropertyInfo = Request.GetType().GetRuntimeProperty(Header.Replace("-", string.Empty));
        // Check if the property is available.
        if (PropertyInfo != null) {
            // Set the value of the header.
            PropertyInfo.SetValue(Request, Value, null);
        } else {
            // Set the value of the header.
            Request.Headers[Header] = Value;
        }
    }

然后你可以这样称呼它:

SendFile("image.jpg", "image/jpg", theByteArray, theClientId, yourAppId, yourApiKey, (result) => {

          //do whatever you want with the result from the server

});

注意我没有实现任何异常处理,你应该在GetResponseStream周围添加一个try-catch,以防服务器给出带有错误代码的响应并从生成的WebException获取响应。