1

他のすべてのメッセージはJSONになるので、Androidソリューションを変換して、JSONマルチパートメッセージを使用してカメラから取得した画像をWCFサービスに送信すると思いました。送信は機能していると思いますが、逆シリアル化する方法がわかりません。私がbase64エンコードを行わない理由は、android 2.1を機能させ、base64エンコードが機能しないためです(少なくともそれは私が読んだものであり、私が見つけた唯一の「ハック」は小さなファイルに対してのみ機能します)。

だからアンドロイドでは私は画像を送ろうとします:

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(Androidからhttpurlconnectとoutputstreamを使用して送信したときのように)コード。それはその時働いていました:D:

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";
    }  

wcfのインターフェイス[OperationContract][WebInvoke(Method = "POST"、UriTemplate = "/ UploadImage"、ResponseFormat = WebMessageFormat.Json、RequestFormat = WebMessageFormat.Json)] string UploadImage(Stream image);

そして、それが重要な場合は、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);
    }

では、質問に移りますが、着信JSONストリームを解析するにはどうすればよいですか?それを行うためのより良い方法はありますか?

注:フィドラーを設定しようとしましたが、3時間経ってもトラフィックを読み取ることができなかったため、utを指定しました。

このコードを実際にデバッグする良い方法はありますか?

ストリームをバイト配列に変換してファイルに保存した場合、結果を含めるのを忘れました。

--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をスキップして、画像のバイト配列を送信するだけの元の状態に戻ることができると思いますが、とにかくJSONメッセージを処理できる必要があります。

これまでのコメントありがとうございます。

4

1 に答える 1

1

私の最初の考えは、それはJSONストリームではないということです。おそらくバイトストリームです。また、イメージが1024バイトより大きい場合、最初の1024バイトを無限に読み書きします。読んだ量を追跡し、その後読み始めるオフセット変数が必要です。

于 2012-10-04T21:24:49.447 に答える