Forum Xamarin.Android

Unable to Post image to server

ranjitrranjitr USMember ✭✭
edited October 2016 in Xamarin.Android

I am trying to Upload a bitmap image to server.
I have converted bitmap image to Byte[] and added as part of MultipartFormDataContent and posted on the specific URL .
I not receiving any response are even callback to httpresponse obj after triggering the PostAsync request.

code:

        var client = new HttpClient ();
        var form = new MultipartFormDataContent ();
        HttpContent content = new ByteArrayContent (imgData);
        form.Add (content, "image/jpeg", "resource.jpg");

        content = new StringContent (claim.claimId);
        form.Add (content, "claimId");
        content = new StringContent (claim.chargeId);
        form.Add (content, "chargeId");
        content = new StringContent (Session.Instance.selectedEmployer.employeeID);
        form.Add (content, "EmployeeId");
        content = new StringContent (Session.Instance.sessionID);
        form.Add (content, "sessionId");

        HttpResponseMessage response = await client.PostAsync (UPLOAD_URL, form);
        if (response.StatusCode == HttpStatusCode.OK) {
            callback (true);
        } else {
            callback (false);
        }

Best Answer

Answers

  • ranjitrranjitr USMember ✭✭

    @Vaikesh K P
    I am currently working on Xamarin.Android not forms.
    I am not trying to create backend to upload images.
    I am not receiving any httpResponse from the webservice.

  • YasirPashaYasirPasha PKMember
    edited October 2016

    Try sending Image in Base64 string format instead of byte[]

    1: Convert Image byte[] into Base64
    private string CreateBase64Image(byte[] fileBytes)
    {
    Image streamImage;
    /* Ensure we've streamed the document out correctly before we commit to the conversion /
    using (MemoryStream ms = new MemoryStream(fileBytes))
    {
    /
    Create a new image, saved as a scaled version of the original /
    streamImage = ScaleImage(Image.FromStream(ms));
    }
    using (MemoryStream ms = new MemoryStream())
    {
    /
    Convert this image back to a base64 string */
    streamImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    return Convert.ToBase64String(ms.ToArray());
    }
    }
    2: send this string as Post parameter (as usual) to your URL

    And On server Side Convert this Base64 string into image

    public static BitmapImage base64image(string base64string)
    {
    byte[] fileBytes = Convert.FromBase64String(base64string);

    using (MemoryStream ms = new MemoryStream(fileBytes))
    {
        Image streamImage = Image.FromStream(ms);
        context.Response.ContentType = "image/jpeg";
        streamImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        return streamImage;
    }
    

    }

  • ranjitrranjitr USMember ✭✭

    @yasir,
    I won't be able to make any changes in the server side to convert base64 back to image.
    I have to send image in byte[]

  • YasirPashaYasirPasha PKMember

    @ranjitr
    Seems you are having trouble getting response
    Try an alternate i.e missing parameter and check weather your server is listening or not.

    P.S: Nothing to do with image uploading

  • ranjitrranjitr USMember ✭✭

    I am able to upload image using postman bit from the app it is failing.
    Is it possible to upload image without converting to byte[] while uploading using **MultipartFormDataContent **
    and upload as file directly to server.

  • ranjitrranjitr USMember ✭✭

    I am still facing issues uploading to server I test on Postman it is working fine.

    Bitmap to byte[] code:
    var stream = new MemoryStream(); icon.Compress(Bitmap.CompressFormat.Png, 0, stream); var checkdata = stream.ToArray();

    Upload image code

    `public static async Task Upload(Claim claim,byte[] image)
    {
    using (var client = new HttpClient())
    {
    using (var content =
    new MultipartFormDataContent())
    {
    content.Add(new ByteArrayContent(image), "file", "resource.png");
    content.Add (new StringContent (claim.claimId), "claimId");
    content.Add (new StringContent (claim.chargeId), "chargeId");
    content.Add (new StringContent (Session.Instance.selectedEmployer.employeeID), "EmployeeId");
    content.Add (new StringContent (Session.Instance.sessionID), "sessionId");
    using (
    var message =
    `` await client.PostAsync(ENV_URL, content))
    {
    var input = await message.Content.ReadAsStringAsync();

                        return input;
                    }
                }
            }
    

    Stack Trace:
    [mono] Unhandled Exception: [mono] System.Net.WebException: Error: SecureChannelFailure (The authentication or decryption has failed.) ---> System.IO.IOException: The authentication or decryption has failed. ---> System.IO.IOException: The authentication or decryption has failed. ---> Mono.Security.Protocol.Tls.TlsException: The authentication or decryption has failed. [mono] at Mono.Security.Protocol.Tls.RecordProtocol.EndReceiveRecord (IAsyncResult asyncResult) [0x0003a] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/RecordProtocol.cs:430 [mono] at Mono.Security.Protocol.Tls.SslClientStream.SafeEndReceiveRecord (IAsyncResult ar, Boolean ignoreEmpty) [0x00000] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs:256 [mono] at Mono.Security.Protocol.Tls.SslClientStream.NegotiateAsyncWorker (IAsyncResult result) [0x00071] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs:418 [mono] --- End of inner exception stack trace --- [mono] at Mono.Security.Protocol.Tls.SslClientStream.EndNegotiateHandshake (IAsyncResult result) [0x00035] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslClientStream.cs:396 [mono] at Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult) [0x0000c] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs:101 [mono] --- End of inner exception stack trace --- [mono] at Mono.Security.Protocol.Tls.SslStreamBase.EndRead (IAsyncResult asyncResult) [0x00051] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/Mono.Security/Mono.Security.Protocol.Tls/SslStreamBase.cs:883 [mono] at Mono.Net.Security.Private.LegacySslStream.EndAuthenticateAsClient (IAsyncResult asyncResult) [0x00011] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/Mono.Net.Security/LegacySslStream.cs:481 [mono] at Mono.Net.Security.Private.LegacySslStream.AuthenticateAsClient (System.String targetHost, System.Security.Cryptography.X509Certificates.X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, Boolean checkCertificateRevocation) [0x00000] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/Mono.Net.Security/LegacySslStream.cs:451 [mono] at Mono.Net.Security.MonoTlsStream.CreateStream (System.Byte[] buffer) [0x0001e] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/Mono.Net.Security/MonoTlsStream.cs:106 [mono] --- End of inner exception stack trace --- [mono] at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00043] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:882 [mono] at System.Threading.Tasks.TaskFactory1[TResult].FromAsyncCoreLogic (IAsyncResult iar, System.Func2 endFunction, System.Action1 endAction, System.Threading.Tasks.Task`1 promise, Boolean requiresSynchronization) [0x00014] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/Tasks/FutureFactory.cs:550
    [mono] --- End of stack trace from previous location where exception was thrown ---
    [mono] at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
    [mono] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
    [mono] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter

    end of stack trace`

    Other logs from xamarin callback window:

    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 System.Runtime.CompilerServices.AsyncMethodBuilderCore.AnonymousMethod__1 (state={System.Runtime.ExceptionServices.ExceptionDispatchInfo}) in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1034 System.Threading.QueueUserWorkItemCallback.WaitCallback_Context (state={System.Threading.QueueUserWorkItemCallback}) in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/threadpool.cs:1307 System.Threading.ExecutionContext.RunInternal (executionContext={System.Threading.ExecutionContext}, callback={System.Threading.ContextCallback}, state={System.Threading.QueueUserWorkItemCallback}, preserveSyncCtx=true) in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/executioncontext.cs:957 System.Threading.ExecutionContext.Run (executionContext={System.Threading.ExecutionContext}, callback={System.Threading.ContextCallback}, state={System.Threading.QueueUserWorkItemCallback}, preserveSyncCtx=true) in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/executioncontext.cs:904 System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/threadpool.cs:1284 System.Threading.ThreadPoolWorkQueue.Dispatch () in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/threadpool.cs:857 System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/threadpool.cs:1212

Sign In or Register to comment.