在 XAMARIN C# 中使用 FILE 发送 POST 请求

查理·洛梅洛

在网上看,我看到了一点如何发布“文件”,因此,我以这种方式编写了代码:

        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;

现在问题又来了……这是我的 API 代码:

<?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);

使用 Postman 它完美地工作,更新数据库中图像的名称并将图像物理插入到指定路径中,响应消息例如是这样的:{"error": false, "message": "Image added successfully - test文件名 = trollolollo.png"}

邮差

德布罗

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 调试器

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

Nicole

Are you sure that you are handling update query correctly ?

如果您搞砸了 SQL 查询或类似的事情,更新查询只会在失败时返回 false。因此,您必须使用mysqli_stmt_affected_rows来查看您的 PHP 代码中的一行是否已更新。

如果邮递员可以做到,HttpClient 也必须能够做到,并且配置正确。

尝试使用邮递员使用的所有标头,您可能遗漏了一些东西,也许文件名导致数据库查询失败。

顺便说一下,您在服务器中处理 jpg 和 png 的方式有什么区别吗?你也可以检查一下。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章