0

我落后于一位 Android 开发人员,他编写了此代码以将图像转换为 base 64 字符串并将其作为 IO.Stream 对象上传到我的 WCF 服务......

    HttpPost post = new HttpPost(mUri);
if(mNameValuePairs != null){
    // creating multipart entity for sending image files 
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);         
    for(int index=0; index < mNameValuePairs.size(); index++) {
        if(mNameValuePairs.get(index).getName().equalsIgnoreCase("strmImage")) {
            // If the key equals to "_strmImage",  use FileBody to transfer the data
            /**
             * to send image as multipart uncomment this line,  currently not used
             */
//                                                  entity.addPart(mNameValuePairs.get(index).getName(), new FileBody(new File (mNameValuePairs.get(index).getValue())));
        /**
         * convert image into byte array
         */
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(mNameValuePairs.get(index).getValue(), options);
            options.inSampleSize = MainActivity.calculateInSampleSize(options,  //downsampling
                    300, 300);
            options.inJustDecodeBounds = false;
            Bitmap bitmap = BitmapFactory.decodeFile(mNameValuePairs.get(index).getValue(), options); 
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
            byte [] byte_arr = stream.toByteArray();
            String image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT); //converting to base 64 string 
            // making the json object and storing it in mPostdata                                           
            mPostdata = new JSONStringer().object()
                    .key("thisImage")
                    .object()
                        .key("UserID").value("163")
                        .key("UserDrugImageID").value("")
                        //.key("Filename").value(mNameValuePairs.get(index).getValue())
                        .key("Filename").value("test.jpg")
                        .key("SetID").value("2ebcbba3-36bb-49ec-8625-43d60fb730ee")
                        .key("strmImage").value(image_str)
                        .endObject().toString();
            Log.e("", mPostdata);

            /**
             * to send image as String body uncomment this line, currently not used 
             */
//                                                  entity.addPart(mNameValuePairs.get(index).getName(), new StringBody(image_str));        
            /**
             * to send image as String body uncomment this line, currently not used 
             */
//                                  entity.addPart(mNameValuePairs.get(index).getName(), new ByteArrayBody(byte_arr, mNameValuePairs.get(index).getValue()));       

        } else {
             // Normal string data
            entity.addPart(mNameValuePairs.get(index).getName(), new StringBody(mNameValuePairs.get(index).getValue()));
        }
    }
    /**
     * setting multipart entity to httppost object, currently not used 
     */
//                                          post.setEntity(entity);

    StringEntity se = new StringEntity(mPostdata);
    se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8                  
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));

    post.setEntity(se);
/*                                          post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");*/
}
HttpResponse response = client.execute(post);
mServerResponse = EntityUtils.toString(response.getEntity());

我编写了 WCF REST 服务,包括这个接受复杂对象的方法:

<OperationContract()> _
<WebInvoke(Method:="POST", UriTemplate:="drugImage/add", RequestFormat:=WebMessageFormat.Json, responseformat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped)> _
Function InsertUserDrugImage(ByVal thisImage As dcUserDrugImage) As dcOperationStatus

Public Function InsertUserDrugImage(ByVal thisImage As dcUserDrugImage) As dcOperationStatus Implements AndroidIService.InsertUserDrugImage

在调试期间,我看到这是我发送的对象:

{"thisImage":{"UserID":"163","UserDrugImageID":"","Filename":"test.jpg","SetID":"2ebcbba3-36bb-49ec-8625-43d60fb730ee","strmImage":"iVBORw0KGgoAAAANSUhEUgAAAUAAAADwCAIAAAD+Tyo8AAAAA3NCSVQICAjb4U\/gAAAKh0lEQVR4\nnO3dz24jWRWA8XNO3XI5GTQLHgS2s5mWEHtgCY8AUtS9avEGrIdmpAEheAN4B3azgxdBGk3\/iV23\n7mFR3dWmldieVN3YJ\/5+i1FLk773pFJf7LiTXF2v1\/JQ7q6qNzc3quruD17nPuOyr169GjdafH3m\n34\/59zuH+W3xXQE8GgIGAiNgIDACBgIjYCAwAgYCI2AgMAIGAiNgIDACBgIjYCAwAgYCI2AgMAIG\nAiNgIDACBgIjYCAwAgYCI2AgMAIGAiNg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CwiMgIHACBgIjICBwAgYCIyAgcAIGAiMgIHACBgIjICBwAgYCIyAgcAIGAiMgIHACBgIjICBwAgY\nCIyAgcAIGAiMgIHACBgIjICBwAgYCIyAgcAIGAiMgIHACBgIjICBwAgYCIyAgcAIGAgs3dzcPPgv\nX8L5q3Mw\/37Mv98x8\/MIDARGwEBgBAwERsBAYAQMBEbAQGAEDARGwEBgBAwERsBAYAQMBEbAQGAE\nDARGwEBgBAwE9j9cgtl23\/xr3AAAAABJRU5ErkJggg==\n"}

这是 dcUserDrugImage 的数据合同...

<Serializable()> _
<DataContract> _
Public Class dcUserDrugImage
    Private _UserDrugImageID As String
    Private _UserID As String
    Private _SetID As String
    Private _url As String
    Private _Filename As String
    Private _strmImage As Stream

    <DataMember(IsRequired:=False)>
    Public Property UserDrugImageID() As String
        Get
            Return _UserDrugImageID
        End Get
        Set(ByVal value As String)
            _UserDrugImageID = value
        End Set
    End Property

    <DataMember(IsRequired:=True)>
    Public Property UserID() As String
        Get
            Return _UserID
        End Get
        Set(ByVal value As String)
            _UserID = value
        End Set
    End Property

    <DataMember(IsRequired:=True)>
    Public Property SetID() As String
        Get
            Return _SetID
        End Get
        Set(ByVal value As String)
            _SetID = value
        End Set
    End Property

    <DataMember(IsRequired:=True)>
    Public Property Filename() As String
        Get
            Return _Filename
        End Get
        Set(ByVal value As String)
            _Filename = value
        End Set
    End Property

    <DataMember(IsRequired:=False)>
    Public Property url() As String
        Get
            Return _url
        End Get
        Set(ByVal value As String)
            _url = value
        End Set
    End Property

    <DataMember(IsRequired:=True)>
    Public Property strmImage() As Stream
        Get
            Return _strmImage
        End Get
        Set(ByVal value As Stream)
            _strmImage = value
        End Set
    End Property

    Public Sub New()
    End Sub

    Public Sub New(ByVal thisDrugImage As UserDrugImage)
        _UserDrugImageID = thisDrugImage.UserDrugImageID
        _UserID = thisDrugImage.UserID
        _SetID = thisDrugImage.SetID
        _url = thisDrugImage.url
        _Filename = thisDrugImage.ImageFileName
    End Sub

    Public Overrides Function ToString() As String
        Dim sb As New StringBuilder
        sb.Append("User ID: ")
        If Not UserID = Nothing Then
            sb.Append(UserID)
        Else
            sb.Append("null")
        End If

        sb.Append(", SetID: ")
        If Not UserID = Nothing Then
            sb.Append(SetID)
        Else
            sb.Append("null")
        End If

        sb.Append(", Filename: ")
        If Not UserID = Nothing Then
            sb.Append(Filename)
        Else
            sb.Append("null")
        End If

        sb.Append(", Size of Image Stream: ")
        If Not strmImage Is Nothing Then
            sb.Append(strmImage.Length.ToString)
        Else
            sb.Append("0")
        End If

        Return sb.ToString
    End Function

End Class

<System.Runtime.Serialization.KnownType(GetType(dcUserDrugImage))> _
<CollectionDataContract()>
Public Class dcDrugImageCollection
    Inherits List(Of dcUserDrugImage)

End Class

我现在得到的错误是:

The server encountered an error processing the request. 

The exception message is 'Cannot create an abstract class.'. 

See server logs for more details. The exception stack trace is: </p>
      <p>   at system.Runtime.Serialization.FormatterServices.nativeGetUninitializedObject(RuntimeType type)...

整天都在用头撞墙,尝试了 39485783475 种不同的东西,只是要休息一下,希望你们中的一个人能看到一些东西 :)

4

1 回答 1

1

正是它Stream给你带来了问题。它是抽象的。考虑改为将其设为字节数组。或者标记为不用于序列化

于 2013-10-02T12:46:42.550 回答