2012-10-04 5 views
1

내 모든 다른 메시지는 JSON이 될 것이므로 JSON multipart 메시지를 사용하여 카메라에서 가져온 이미지를 보내도록 내 안드로이드 솔루션을 변환한다고 생각했습니다. 나는 보내는 일이 있다고 생각하지만 비 직렬화하는 방법을 모른다. 내가 base64 인코딩하지 않는 이유는 android 2.1이 작동하고 base64 인코딩이 작동하지 않기를 바라는 것입니다. (적어도 내가 읽었던 것이고 작은 파일에 대해서만 작동하는 "해킹"만 있습니다.)JSON 및 MultipartEntity를 사용하여 Android에서 WCF로 이미지 전송

그래서 안드로이드에서 나는 이미지를 보내려고 :

public void upload() throws Exception { 
    //Url of the server 
    String url = "http://192.168.0.10:8000/service/UploadImage"; 
    HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(url); 
    MultipartEntity mpEntity = new MultipartEntity(); 
    //Path of the file to be uploaded 
    String filepath = path; 
    File file = new File(filepath); 
    ContentBody cbFile = new FileBody(file, "image/jpeg");  

    //Add the data to the multipart entity 
    mpEntity.addPart("image", cbFile); 
    post.setEntity(mpEntity); 
    //Execute the post request 
    HttpResponse response1 = client.execute(post); 
    //Get the response from the server 
    HttpEntity resEntity = response1.getEntity(); 
    String Response=EntityUtils.toString(resEntity); 
    Log.d("Response:", Response); 

    client.getConnectionManager().shutdown(); 
} 

WCF를 (그것이 나는 안드로이드에서 httpurlconnect과의 OutputStream을 사용하여 보낼 때) 코드. 그런 다음 작동되었다 : D 다음 WCF위한

public string UploadImage(Stream image) 
    { 
     var buf = new byte[1024]; 
     var path = Path.Combine(@"c:\tempdirectory\", "test.jpg"); 
     int len = 0; 
     using (var fs = File.Create(path)) 
     { 
      while ((len = image.Read(buf, 0, buf.Length)) > 0) 
      { 
       fs.Write(buf, 0, len); 
      } 
     } 
     return "hej"; 
    } 

인터페이스 [OperationContract를] [WebInvoke의 ( METHOD = "POST" UriTemplate = "/ UploadImage"ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] string UploadImage (이미지 스트림);

그리고 중요한 경우

, 질문에 그래서 이제 WCF를

static void Main(string[] args) 
    { 
     string baseAddress = "http://192.168.0.10:8000/Service"; 
     ServiceHost host = new ServiceHost(typeof(ImageUploadService), new Uri(baseAddress)); 
     WebHttpBinding binding = new WebHttpBinding(); 
     binding.MaxReceivedMessageSize = 4194304; 

     host.AddServiceEndpoint(typeof(IImageUploadService),binding , "").Behaviors.Add(new WebHttpBehavior()); 
     host.Open(); 
     Console.WriteLine("Host opened"); 
     Console.ReadKey(true); 
    } 

를 실행하는 consoleapplication은 내가 어떻게 incomming JSON 스트림을 구문 분석합니까? 그것을 할 수있는 더 좋은 방법이 있습니까?

참고 : 필라델피아를 설정하려고했지만 트래픽을 읽지도 못하는 3 시간이 지난 후에도 필자에게 전달했습니다.

실제로이 코드를 디버깅하는 좋은 방법이 있습니까?

--IZZI8NmDZ-Id7DWP5z0nuPPZspVAGglcfEY9 
    Content-Disposition: form-data; name="image"; filename="mypicture.jpg" 
    Content-Type: image/jpeg 
    Content-Transfer-Encoding: binary 

    ÿØÿá°Exif and other funny letters of cause :D ending with 
    --IZZI8NmDZ-Id7DWP5z0nuPPZspVAGglcfEY9-- 

를 새로운 코드로 나는이

--crdEqve1GThGGKugB3On0tGNy5h2u746 
Content-Disposition: form-data; name="entity" 

{"filename":"mypicture.jpg"} 
--crdEqve1GThGGKugB3On0tGNy5h2u746 
Content-Disposition: form-data; name="file"; filename="mypicture.jpg" 
Content-Type: application/octet-stream 

ÿØÿá´Exif and the whole image here ... 

새로운 업데이 트를 얻을 관리 할 수 ​​있습니다

내가 바이트 배열 스트림을 변환하고 그 파일에 저장하면 결과를 포함하도록 잊어 버렸 루틴은 다음과 같습니다 :

public void uploadFile() { 
     String filepath = path; 
      File file = new File(filepath); 
     HttpClient httpClient = new DefaultHttpClient(); 

     HttpPost postRequest = new HttpPost("http://192.168.0.10:8000/service/UploadImage"); 
     ResponseHandler<String> responseHandler = new BasicResponseHandler(); 

     // Indicate that this information comes in parts (text and file) 
     MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

     try { 

      //Create a JSON object to be used in the StringBody 
      JSONObject jsonObj = new JSONObject(); 

      //Add some values 
      jsonObj.put("filename", file.getName()); 

      //Add the JSON "part" 
      reqEntity.addPart("entity", new StringBody(jsonObj.toString())); 
     } 
     catch (JSONException e) { 
      Log.v("App", e.getMessage()); 
     } 
     catch (UnsupportedEncodingException e) { 
      Log.v("App", e.getMessage()); 
     } 

     FileBody fileBody = new FileBody(file);//, "application/octet-stream"); 
      reqEntity.addPart("file", fileBody); 

      try { 
       postRequest.setEntity(reqEntity); 

       //Execute the request "POST" 
      HttpResponse httpResp = httpClient.execute(postRequest); 

      //Check the status code, in this case "created" 
      if(((HttpResponse) httpResp).getStatusLine().getStatusCode() == HttpStatus.SC_CREATED){ 
       Log.v("App","Created"); 
      } 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
    } 

그래도 나는 다른 스트림의 일부로 json 메시지 부분 (나 필요할 경우)을 나눌 수 있고 이미지를 저장하기위한 별도의 파트로 이미지를 가져올 수 있습니다. json을 건너 뛰고 이미지의 bytearray를 보내는 원본으로 돌아갈 수는 있지만 JSON 메시지를 처리 ​​할 수 ​​있어야합니다.

의견을 보내 주셔서 감사합니다.

답변

1

첫 번째 생각은 JSON 스트림이 아니라는 것입니다. 그것은 아마도 바이트 스트림입니다. 또한 이미지가 1024 바이트보다 큰 경우 처음 1024 바이트를 무한히 읽고 쓸 것입니다. 읽은 양을 추적하고 그 후에 읽기를 시작하는 오프셋 변수가 있어야합니다.

+0

바이트 스트림 일 수도 있습니다. 내 지식은 매우 새롭습니다. D. 그러나 청크 당 1024 바이트를 읽고 파일로 출력합니다. 나는이 파일의 일부를 추가했다.이 파일은 거의 2MB 크기로 정확하다. – Todilo

+1

확실히 텍스트가 아닌 바이트 스트림입니다. [this] (http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx)에서 Stream.read() 사용에 대한 Microsoft의 샘플 코드를 확인하십시오. – toadzky

관련 문제