HTTP POST multipart form-data

CrossSharpCrossSharp Member ✭✭
edited July 2019 in Xamarin.iOS


I am making a cross-platform app using xamarin forms, and I need to make Http post in the background.

I managed to do that with a foreground service and HttpClient in Android.

I am not able to do it in IOS, I am using NSUrlSession, for the backgrounding task.

I was able to do a POST with application/x-www-form-urlencoded; charset=UTF-8 as a Content-Type.

But I wasn't able to do it with multipart form-data.

I've read somewhere that I have to build the body of the request myself so I did it using some swift and objective C translations, but I was unsuccesful.

This is my code Please help!

using (var url = NSUrl.FromString(UploadUrlString))
        using (var request = new NSMutableUrlRequest(url))
            string boundaryConstant = "------WebKitFormBoundaryXXXXXXXXXX";
            request.HttpMethod = "POST";
            request["Cookie"] = "SERVERIDXXX=XXXXXX";
            var data = NSData.FromArray(ImageByteArray);
            var uiimage = UIImage.LoadFromData(data);
            NSData img = uiimage.AsJPEG(1);
            string Body = boundaryConstant+ "\r\n";
            Body += "Content-Disposition: form-data; name=\"id\"\r\n\r\n";
            //Body += StaticData.Photos[0].Round;
            Body += 50000+ "\r\n";
            Body += boundaryConstant + "\r\n";
            Body += "Content-Disposition: form-data; name=\"upload_file\"; filename=\"Untitled.png\"\r\n";
            Body += "Content-Type: image/png\r\n\r\n";
            Body+=img+ "\r\n";
            Body += boundaryConstant + "--";
            request.Body = NSData.FromString(Body);
            request["Content-Type"] = "multipart/form-data; boundary="+ boundaryConstant;
            NSUrlSessionDownloadTask downloadTask = session.CreateDownloadTask(request);
Sign In or Register to comment.