简体   繁体   English

如何将图像从Android发送到WCF服务器?

[英]How to send an image from Android to a WCF server?

I working on sending an image from Android to a WCF server. 我正在尝试将图像从Android发送到WCF服务器。 I tried sending the FileBOdy in a multi-part body, but that didn't get the job done. 我尝试将FileBOdy分为多个部分发送,但这并没有完成任务。 Finally I tried sending a ByteArrayBody in a multi-part body. 最后,我尝试在多部分主体中发送ByteArrayBody。 It did work, but I got a corrupted image in server. 它确实起作用,但是服务器中的图像损坏。 I googled a lot, but couldn't get an acceptable solution to my problem. 我在Google上搜索了很多,但是无法解决我的问题。 Can any one spot a mistake in my Android or WCF code? 有人可以在我的Android或WCF代码中发现错误吗?

Android code Android代码

ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();

// Making HTTP request
try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();

    String URL1 = "http://rohit-pc:8078/service1.svc/UploadImage";

    HttpPost httpPost = new HttpPost(URL1);

    ContentBody bin = null;
    MultipartEntity reqEntity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);

    ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");

    reqEntity.addPart("image", bab);
    reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));

    httpPost.setEntity(reqEntity);

    HttpResponse response = httpClient.execute(httpPost);
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent(), "UTF-8"));
    String sResponse;
     s = new StringBuilder();

    while ((sResponse = reader.readLine()) != null) {
        s = s.append(sResponse);
    }
    System.out.println("Response: " + s);
} catch (Exception e) {
    Log.e(e.getClass().getName(), e.getMessage());
}

WCF code WCF代码

public string GetStream(Stream str,string filename) {

        Guid guid = Guid.NewGuid();
        string Path = System.Web.Hosting.HostingEnvironment.MapPath("~/Images");
        FileStream file = new FileStream(Path + "/" +filename, FileMode.Create);

        byte[] bytearray = new byte[100000000];

        int bytesRead, totalBytesRead = 0;
        do {
            bytesRead = str.Read(bytearray, 0, bytearray.Length);
            totalBytesRead += bytesRead;
        } while (bytesRead > 0);

        file.Write(bytearray, 0, bytearray.Length);
        file.Close();
        file.Dispose();

       return "Success";
    }

我会说使用Base64格式发送以base64格式编码的图像作为字符串。

Sorry to answer an old question. 很抱歉回答一个老问题。 But I had spent over 5 hours to figure out the issue. 但是我花了5个多小时才弄清楚这个问题。 So would like to share the solution I found. 所以想分享我找到的解决方案。 My issue was a corrupted image saved in the server . 我的问题是服务器中保存的图像损坏

Actually, WCF does not have an effective way of parsing the multipart form data. 实际上,WCF没有解析多部分表单数据的有效方法。 Thats why the suggestion from MS is to use the raw stream to transmit images to wcf services. 因此,MS的建议是使用原始流将图像传输到wcf服务。

So after a few hours of struggling to get rid of MultipartEntity(replaced with ByteArrayEntity), I finally got it working by using the below code. 因此,经过数小时的努力摆脱了MultipartEntity(用ByteArrayEntity替换),我终于使用下面的代码使它工作了。 Hope this should help some one. 希望这会有所帮助。

Android 安卓系统

Bitmap bm = BitmapFactory.decodeFile(params[0]);

ByteArrayOutputStream bos = new ByteArrayOutputStream();

bm.compress(CompressFormat.JPEG, 75, bos);

byte[] data = bos.toByteArray();
// the below is the important one, notice no multipart here just the raw image data 
request.setEntity(new ByteArrayEntity(data));

then the rest of the actual http client continues. 然后其余的实际http客户端继续。

Wcf Interface Wcf接口

<OperationContract()>
<WebInvoke(Method:="POST",
     ResponseFormat:=WebMessageFormat.Json,
     BodyStyle:=WebMessageBodyStyle.Bare,
     UriTemplate:="/UploadPhoto?UsedCarID={UsedCarID}&FileName={FileName}")>
Sub UploadPhoto(UsedCarID As Integer, FileName As String, FileContents As Stream)

This is my first post at Stack Overflow thank you so much. 这是我在Stack Overflow上的第一篇文章,非常感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM