2016-02-04 28 views
0

我想發送一個imagedata到我的數據庫,但我不知道如何讓它工作。這是我當前的代碼:試圖發送一個ImageData到我的數據庫

這是我的數據庫csfile,我試圖創建一個圖像到我的數據庫(它正在工作,但我不知道如果我應該發送它作爲字節[]作爲我的數據庫需要它作爲一個文件)

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,我創建包含圖象 - 字節圖象 - :

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; 
    } 
+0

我看不到將代碼存儲到數據庫的代碼,相關的代碼確實在parseAPI.createInfo中,如果它接受一個字節數組,那麼代碼是正確的,一個文件只是一堆字節,在數據庫中,「文件」或「圖像」字段類型等等都表示字節數組。 – Gusman

+0

用更多來自createInfo的代碼更新了它。只是向下滾動到末尾 – DiddanDo

+0

你的答案是在你的代碼中,它只需要一個字節數組,所以一切都很好;) – Gusman

回答

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 

}); 

當心我沒有實現的任何異常處理,你應該添加圍繞一個try-catch GetResponseStream使用萬一服務器給出一個錯誤代碼的響應並從生成的WebException中獲取響應。

+0

試圖寫它,以便Xamarin可以運行它。我想用httpclientrequest替換httpwebrequest。不知道我應該如何達到方法,contenttype,contentlength等 – DiddanDo

+0

我不承認所有的代碼,所以有很多紅色代碼,我試圖取代但不太確定。 – DiddanDo

+0

哦,上帝,對不起,我忘記了Xamarin,讓我重寫它。 – Gusman

相關問題