Forum Xamarin.iOS

Announcement:

The Xamarin Forums have officially moved to the new Microsoft Q&A experience. Microsoft Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

To create new threads and ask questions head over to Microsoft Q&A for .NET and get involved today.

take picture and upload it to server

I am trying to create an app which allows user to take picture and then picture will upload on server using rest api.

Here is the code in Xamarin (able to get the picture and convert it to memory stream)

private async void CameraButton_Clicked(object sender, EventArgs e)
{
byte[] photobyte = null;
try
{
var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
if (photo != null)
{
using (var memoryStream = new MemoryStream())
{
photo.GetStream().CopyTo(memoryStream);
photo.Dispose();
photobyte = memoryStream.ToArray();
var image = new Image
{
Source = ImageSource.FromStream(() => new MemoryStream(photobyte))
};
PhotoImage.Source = image.Source;
using (var client = new HttpClient())
{
var apiUri = new Uri("http://mobile.xxxx.co/RestServiceImpl.svc/user/PostUserImage");

                        //load the image byte[] into a System.Net.Http.ByteArrayContent
                        var imageBinaryContent = new ByteArrayContent(photobyte);

                        var multipartContent = new MultipartFormDataContent();
                        multipartContent.Add(imageBinaryContent, "sudhir.png"); 
                        var result = await client.PostAsync(apiUri, multipartContent);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            DisplayAlert("dd", ex.Message, "Cancel");
        }
    }

API method on server

[HttpRoute("user/PostUserImage")]
[AllowAnonymous]
public async Task PostUserImage()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
try
{

            var httpRequest = HttpContext.Current.Request;

            foreach (string file in httpRequest.Files)
            {
                HttpRequestMessage Request = new HttpRequestMessage();
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created,"");

                var postedFile = httpRequest.Files[file];
                if (postedFile != null && postedFile.ContentLength > 0)
                {

                    int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  

                    IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                    var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                    var extension = ext.ToLower();
                    if (!AllowedFileExtensions.Contains(extension))
                    {

                        var message = string.Format("Please Upload image of type .jpg,.gif,.png.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else if (postedFile.ContentLength > MaxContentLength)
                    {

                        var message = string.Format("Please Upload a file upto 1 mb.");

                        dict.Add("error", message);
                        return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                    }
                    else
                    {



                        var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);

                        postedFile.SaveAs(filePath);

                    }
                }

                var message1 = string.Format("Image Updated Successfully.");
                return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
            }
            var res = string.Format("Please Upload a image.");
            dict.Add("error", res);
            //return Request.CreateResponse(HttpStatusCode.NotFound,"", dict);
            return null;
        }
        catch (Exception ex)
        {
            var res = string.Format("some Message");
            dict.Add("error", res);
            return null;
            //return Request.CreateResponse(HttpStatusCode.NotFound, dict);
        }
    }

any ideas how to do that?

Answers

  • Ahsan_SiddiqueAhsan_Siddique PKMember ✭✭✭✭

    @sudhirbharti.5023 said:
    I am trying to create an app which allows user to take picture and then picture will upload on server using rest api.

    Here is the code in Xamarin (able to get the picture and convert it to memory stream)

    private async void CameraButton_Clicked(object sender, EventArgs e)
    {
    byte[] photobyte = null;
    try
    {
    var photo = await Plugin.Media.CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions() { });
    if (photo != null)
    {
    using (var memoryStream = new MemoryStream())
    {
    photo.GetStream().CopyTo(memoryStream);
    photo.Dispose();
    photobyte = memoryStream.ToArray();
    var image = new Image
    {
    Source = ImageSource.FromStream(() => new MemoryStream(photobyte))
    };
    PhotoImage.Source = image.Source;
    using (var client = new HttpClient())
    {
    var apiUri = new Uri("http://mobile.xxxx.co/RestServiceImpl.svc/user/PostUserImage");

    //load the image byte[] into a System.Net.Http.ByteArrayContent
    var imageBinaryContent = new ByteArrayContent(photobyte);

    var multipartContent = new MultipartFormDataContent();
    multipartContent.Add(imageBinaryContent, "sudhir.png");
    var result = await client.PostAsync(apiUri, multipartContent);
    }
    }
    }
    }
    catch (Exception ex)
    {
    DisplayAlert("dd", ex.Message, "Cancel");
    }
    }

    API method on server

    [HttpRoute("user/PostUserImage")]
    [AllowAnonymous]
    public async Task PostUserImage()
    {
    Dictionary<string, object> dict = new Dictionary<string, object>();
    try
    {

                var httpRequest = HttpContext.Current.Request;
    
                foreach (string file in httpRequest.Files)
                {
                    HttpRequestMessage Request = new HttpRequestMessage();
                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created,"");
    
                    var postedFile = httpRequest.Files[file];
                    if (postedFile != null && postedFile.ContentLength > 0)
                    {
    
                        int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB  
    
                        IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
                        var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                        var extension = ext.ToLower();
                        if (!AllowedFileExtensions.Contains(extension))
                        {
    
                            var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
    
                            dict.Add("error", message);
                            return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                        }
                        else if (postedFile.ContentLength > MaxContentLength)
                        {
    
                            var message = string.Format("Please Upload a file upto 1 mb.");
    
                            dict.Add("error", message);
                            return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
                        }
                        else
                        {
    
    
    
                            var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);
    
                            postedFile.SaveAs(filePath);
    
                        }
                    }
    
                    var message1 = string.Format("Image Updated Successfully.");
                    return Request.CreateErrorResponse(HttpStatusCode.Created, message1); ;
                }
                var res = string.Format("Please Upload a image.");
                dict.Add("error", res);
                //return Request.CreateResponse(HttpStatusCode.NotFound,"", dict);
                return null;
            }
            catch (Exception ex)
            {
                var res = string.Format("some Message");
                dict.Add("error", res);
                return null;
                //return Request.CreateResponse(HttpStatusCode.NotFound, dict);
            }
        }
    

    any ideas how to do that?

    I am referring you a video that can help you to solve your problem. Please watch this video.

    https://youtube.com/watch?v=IVvJX4CoLUY

Sign In or Register to comment.