Forum Xamarin.Forms

how to upload image to the server using api in xamarin forms?

API : http://hallpassapi.jamsocialapps.com/api/profile/UpdateProfilePicture/
Method: Post (multipart/form-data)
Parameter : StudentId=2123

Tagged:

Answers

  • JSparrowJSparrow USMember

    No I want to select image from gallery, So how will it work? Can you send me a small zip file...

  • ThomasBurkhartThomasBurkhart DEMember ✭✭✭✭

    Bikash, this is not the first time, that you ask if someone can do your work for you. Please stopp thos sort of questions.
    If you have a specific problem, you can always ask

  • Maharshi.5212Maharshi.5212 USMember ✭✭

    @Bikash00789
    I offer a simple solution to this problem , put some bounty on the task you want to achieve and then somebody might be willing to write the code for you.

  • Gracias, me sirvió de mucho saludos.

    @AdamBennett.7253 said:
    this is how I do it:

      private async void UploadImage()
      {
          //variable
                  var url = "http://hallpassapi.jamsocialapps.com/api/profile/UpdateProfilePicture/";
              var file = "path/to/file.ext";
    
                  try
                  {
                        //read file into upfilebytes array
                        var upfilebytes = File.ReadAllBytes(file);
                        
                        //create new HttpClient and MultipartFormDataContent and add our file, and StudentId
                        HttpClient client = new HttpClient();
                      MultipartFormDataContent content = new MultipartFormDataContent();
                      ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
                      StringContent studentIdContent = new StringContent("2123");
                      content.Add(baContent, "File", "filename.ext");
                      content.Add(studentIdContent, "StudentId");
        
        
                        //upload MultipartFormDataContent content async and store response in response var
                        var response =
                          await client.PostAsync(url, content);
        
                        //read response result as a string async into json var
                        var responsestr = response.Content.ReadAsStringAsync().Result;
        
                        //debug
                        Debug.WriteLine(responsestr);
                    
                  }
                  catch (Exception e)
                  {
                        //debug
                      Debug.WriteLine("Exception Caught: " + e.ToString());
        
                        return;
                  }
      }
    obviously you would need to change var file with the path to your file, and change filename.ext to the name of the file you want to upload it to, and File to the required field the api needs for the file.
    
  • RaulBastianRaulBastian USMember ✭✭
    edited February 2017

    @AdamBennett.7253 Is File.ReadAllBytes your own implementation? A Plugin?

  • DanCohenDanCohen USMember
    edited February 2017
  • wjjungwjjung USMember

    System.IO.File ~ is no avaliable in PCL!!
    need extra solution..

  • sumitsisodia.9614sumitsisodia.9614 USMember ✭✭

    Hello wj jung, is you got solution for System.IO.File

  • Still no solution to this?

  • RobertoAlvaradoRobertoAlvarado COUniversity

    Hi

    @PhathuKhabubu try send a stream how parameter to this method, and the

    var upfilebytes = File.ReadAllBytes(file);

    You can replace with :

    MemoryStream ms = new MemoryStream();
    stream.CopyTo(ms);
    ByteArrayContent baContent = new ByteArrayContent(ms.ToArray());

    Best Regards.

  • FB123FB123 CAMember ✭✭
    edited April 2018

    Unfortunately when I try to upload a file I get the following exception

    System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.IO.IOException: Error writing request ---> System.Net.Sockets.SocketException: The socket has been shut down
    at System.Net.WebConnection.EndWrite (System.Net.HttpWebRequest request, System.Boolean throwOnError, System.IAsyncResult result)

    If I comment out the
    content.Add(baContent, "File", "filename.jpg");

    The requests hits the server (and although there is no file to process) it works.

    Any idea why I'm getting this socket issue?
    (it's not a big file only 864952 bytes)

    And the server works fine when I post the file to it with Postman

  • In my case, this code works perfectly for UploadFIle to WebService AspNet c# Asmx

    My webservice was build in c# asmx

    Server side asmx
    [WebMethod]
    public void TransferFile()
    {
    var arquivo = HttpContext.Current.Request.Form["ap"];
    byte[] arquivoBytes = System.Convert.FromBase64String(arquivo);
    Context.Response.Write("OK");
    }

    Xamarin Side , Uploading image base64

    byte[] byteData;
    byteData = System.IO.File.ReadAllBytes(path of file);
    HttpClient client = new HttpClient();
    MultipartFormDataContent content = new MultipartFormDataContent();
    var memoryStream = new MemoryStream(byteData);

    HttpClient client = new HttpClient();
    MultipartFormDataContent content = new MultipartFormDataContent();
    content.Add(new StringContent(Convert.ToBase64String(byteData)), "ap");

    var response =
    await client.PostAsync("yourwebservice/TransferFile", content);

    var responsestr = response.Content.ReadAsStringAsync().Result;

    hope help you

  • WonderboyWonderboy ZAMember ✭✭

    Hellos All,
    Please kindly assist clarify, I am wanting to save an image file from iPhone to server path. I have followed the thread using the code @AdamBennett.7253 , but am unfortunately getting an error message.
    Please assist with following questions:
    0. I am able to select the file and read its contents
    1.Do I need to do any work on the server side for the example to work?
    2. I want the file to be name "sisi.png" on the server side, but am not sure what the section below actually does:

    ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
    content.Add(baContent, "File", "filename.ext");

    1. The error message that gets returned:

    <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n\r\n\r\n\r\n405 - HTTP verb used to access this page is not allowed.\r\n\r\n\r\n\r\n\r\n\r\n

    Server Error

    \r\n

    \r\n
    \r\n

    405 - HTTP verb used to access this page is not allowed.

    \r\n

    The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.

    \r\n
    \r\n

    \r\n\r\n\r\n"

    Thanks in advance for assistance

    Thulani

  • XavierPerseguersXavierPerseguers CHMember ✭✭✭

    @Wonderboy You should google "405 - HTTP verb used to access this page is not allowed." and then you would find something related to the method you used to send the file. Did not have much reading of what you actually did, but my gut feeling is that you use PUT to send your file and your server does not support that. So either fix your server to accept extended verbs such as PUT, DELETE, PATCH and alike or stick to GET/POST (in that case POST instead of PUT).

  • WonderboyWonderboy ZAMember ✭✭

    @XavierPerseguers , I really appreciate your response.
    I actually did not have a receiving service on the server side. An example found on stack overflow, helped a lot. Herewith the link to it.
    https://stackoverflow.com/questions/27425043/upload-image-using-httpclient

  • KhairulFLPMKhairulFLPM Member ✭✭

    Hi guys.. I use @AdamBennett.7253 code and looks good so far, but how will I received the passed multipart data in my webapi? I try using below code (refer to https://www.codeproject.com/Questions/1201467/Read-multipartformdatacontent-using-web-api ), but does not give any response..

    //my api
    [HttpPost]
    [Route("api/PostPhoto/Upload")]
    public async Task Upload()
    {
    //Error checking here to require multi part for form uploads
    if (!Request.Content.IsMimeMultipartContent())
    {
    return BadRequest(string.Format(@Forever2U Media type is unsupported for file upload));
    }

            //In your API project you should have a /Content directory, this is a directory under /Content called uploads. You can name whatever you want here as long as
            //  the directory exists
            string root = HttpContext.Current.Server.MapPath("~/Documents/FBOPhoto");
            Directory.CreateDirectory(root);
            var provider = new MultipartFormDataStreamProvider(root);
    
            // This is how you would get any variables, other than your file, that came along with your upload. In your example you had textname and textname2. Below is how you
            //  could go about retrieving those values
            var yourTextNameVariableInYourQuestion = provider.FormData.GetValues("StudentId").Select(m => m).FirstOrDefault();
    
            await Request.Content.ReadAsMultipartAsync(provider);
    
            foreach (var file in provider.FileData)
            {
                FileInfo fileInfo = new FileInfo(file.LocalFileName);
    
                if (fileInfo.Length != 0)
                {
                    // Pretty self explanatory. I rename the file that is uploaded to something else, web api defaults the names to something like body_part****** so when I upload
                    //   files in web api I go ahead and rename it to what the uploaded file name was.
                    string newFileName = file.LocalFileName +
                                         Path.GetExtension(
                                             file.Headers.ContentDisposition.FileName
                                                 .Replace("\"", string.Empty)
                                                 .Replace(@"\", string.Empty));
    
                    global::System.IO.File.Move(file.LocalFileName, newFileName);
    
                }
            }
    
            // This has no error catching or anything so if something dies in the above, this will explode. Include proper error handling as you see fit
            return Ok();
        }
    
  • saidtamimsaidtamim Member ✭✭
    edited July 1

    @AdamBennett.7253 said:
    @Bikash00789

    I would download Xam.Plugin.Media from Nuggets and use that to pick the image from the gallery with the following code:

                  //initialize our media plugin
                        var media = CrossMedia.Current;
                        
                        //pick photo
                        var file = await media.PickPhotoAsync();
    
                        // wait until the file is written
                        while (File.ReadAllBytes(file.Path).Length == 0)
                        {
                            System.Threading.Thread.Sleep(1);
                        }
    

    then just add that to the previous code as follows:

      private async void UploadImage()
            {
              //variable
                    var url = "http://hallpassapi.jamsocialapps.com/api/profile/UpdateProfilePicture/";
                
                    try
                    {
                   //initialize our media plugin
                     var media = CrossMedia.Current;
                            
                      //pick photo
                       var file = await media.PickPhotoAsync();
        
                       // wait until the file is written
                       while (File.ReadAllBytes(file.Path).Length == 0)
                        {
                             System.Threading.Thread.Sleep(1);
                        }
    
                        //read file into upfilebytes array
                        var upfilebytes = File.ReadAllBytes(file);
    
                        //create new HttpClient and MultipartFormDataContent and add our file, and StudentId
                        HttpClient client = new HttpClient();
                        MultipartFormDataContent content = new MultipartFormDataContent();
                        ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
                        StringContent studentIdContent = new StringContent("2123");
                        content.Add(baContent, "File", "filename.ext");
                        content.Add(studentIdContent, "StudentId");
    
    
                        //upload MultipartFormDataContent content async and store response in response var
                        var response =
                            await client.PostAsync(url, content);
    
                        //read response result as a string async into json var
                        var responsestr = response.Content.ReadAsStringAsync().Result;
    
                        //debug
                        Debug.WriteLine(responsestr);
    
                    }
                    catch (Exception e)
                    {
                        //debug
                        Debug.WriteLine("Exception Caught: " + e.ToString());
    
                        return;
                    }
        }
    

    At least that's how I would do it anyways. I'm new to all this though so ymmv

    This line var upfilebytes = File.ReadAllBytes(file); is not working the message is (connot convert from plugin.media.abstractions to to string) how you fix this

  • saidtamimsaidtamim Member ✭✭

    @AdamBennett.7253
    @Bikash00789

    //read file into upfilebytes array
    var upfilebytes = File.ReadAllBytes(file);

    error: connot convert from plugin.media.abstractions to to string

Sign In or Register to comment.