Search code examples
c#filexamarinposthttpclient

Sending a POST request with FILE using in XAMARIN C#


looking on the web, I saw a little bit how to POST a 'file' and therefore, I wrote my code in this way:

        var upfilebytes = File.ReadAllBytes((string)fPath);

        //create new HttpClient and MultipartFormDataContent and add our file, and StudentId
        HttpClient client = new HttpClient();

        MultipartFormDataContent content = new MultipartFormDataContent();
        ByteArrayContent baContent = new ByteArrayContent(upfilebytes);
        content.Add(baContent, "img", fPath);

        StringContent emailText = new StringContent(lbl_email.Text);
        content.Add(emailText, "email");

        string url = "http://192.168.178.77/TestLoginURL/api/updateUserImage.php";
        //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;

now the problem is another ... this is my API code:

<?php
$response = array();

if($_SERVER['REQUEST_METHOD']=='POST'){

    //getting values
    $img = $_FILES['img']['name'];
    $email = $_POST['email'];

    //including the db operation file
    require_once '../includes/DbOperation.php';

    $db = new DbOperation();

    $target = "/Applications/XAMPP/xamppfiles/htdocs/TestLoginURL/images/".basename($img);

    //inserting values
    if($db->updateImage((String)basename($img),$email)){
        $response['error']=false;
        $response['message']='Image added successfully - test fileName = '.(String)basename($img);
    }else{
        $response['error']=true;
        $response['message']='Could not add image';
    }
    if(move_uploaded_file($_FILES['img']['tmp_name'], $target)) {
        /*$response['error']=false;
        $response = "Image uploaded successfully";*/
    }else{
        $response['error']=true;
        $response = "Failed to upload image";
    }
}else{
    $response['error']=true;
    $response['message']='You are not authorized';
}
echo json_encode($response);

With Postman it works perfectly, updates the name of the image in the database and physically inserts the image in the designated path and the response message for example is this: {"error": false, "message": "Image added successfully - test fileName = trollolollo.png"}

postman

dbrow

Now, the app saves the file in the right repository but does NOT UPDATE the name of the 'image' in the database ... BUT strangely, the "response" message in the debugger also correctly shows the name of the FILE ... So I just don't understand where I'm wrong ... Could someone help me with the code please? Thanks

xamarinvs debugger

OFF_TOPIC: usually, when I have to send only strings, I send a post request written in this way

            string url = "http://192.168.178.77/TestLoginURL/api/insertUser.php";

            FormUrlEncodedContent formContent = new FormUrlEncodedContent(new[]
            {
              new KeyValuePair<string, string>("nickname", nickname),
              new KeyValuePair<string, string>("password", password1),
              new KeyValuePair<string, string>("email", email)
            });

            var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                var responseMessage = httpClient.PostAsync(url, formContent).Result;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                throw;
            }

but now, being a file and having no experience about it I am having difficulties... thanks again, I hope someone can help me with the code


Solution

  • Are you sure that you are handling update query correctly ?

    Update query will only return false on a failure if you messed up the SQL query or anything like that. So you have to use mysqli_stmt_affected_rows to see if a row has been updated in your PHP code.

    If postman can do it HttpClient must be able to do it too, with the proper configuration.

    Try to use all the headers postman is using you are probably missing something, maybe the filename is causing the DB query to fail.

    By the way is there any difference between how you handle jpg and png in your server ? you can check that too.