【问题标题】:Sending a POST request with FILE using in XAMARIN C#在 XAMARIN C# 中使用 FILE 发送 POST 请求
【发布时间】:2019-08-11 15:42:03
【问题描述】:

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

        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成功 - 测试文件名 = trollolollo.png"}

现在,应用程序将文件保存在正确的存储库中,但没有更新数据库中“图像”的名称……但奇怪的是,调试器中的“响应”消息也正确显示了文件的名称...所以我只是不明白我错在哪里...有人可以帮我写代码吗?谢谢

OFF_TOPIC:通常,当我只需要发送字符串时,我会发送这样写的 post 请求

            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;
            }

但是现在,作为一个文件并且没有经验,我遇到了困难...... 再次感谢,希望有人能帮我写代码

【问题讨论】:

  • 在 Xamarin 代码中,您似乎将“img”参数设置为文件的完整路径,而不仅仅是文件名
  • 是的,这样我的 API 可以识别文件和名称,正如您在调试器屏幕截图中看到的那样......我错了吗?我应该单独尝试这条路吗?然后如果还有其他文件,他还能如何选择正确的文件?我应该如何更改代码? (请原谅大量的问题,但我想尽可能多地理解 XD)@Jason - 作为问题的解决方案,我可以提出 2 个不同的发布请求......一个移动目录中的图像,另一个移动到只需更改数据库表中的名称......但在我看来这是一个可怕的解决方案。
  • 你的服务器不需要知道整个路径,它只关心文件名
  • 我以这种方式更改了代码“ ByteArrayContent baContent = new ByteArrayContent(upfilebytes); content.Add(baContent, "img", fileName); “谢谢,您对路径的看法是正确的,但不幸的是我仍然有同样的问题......图像保存在服务器上的文件夹中,即使在进行查询后调试器也会返回正确的名称,但实际上数据库没有使用名称更新...... :( @Jason
  • 那么你需要调试你的PHP代码来找出为什么db更新不起作用

标签: c# file xamarin post httpclient


【解决方案1】:

您确定您正在正确处理更新查询吗?

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

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

尝试使用邮递员正在使用的所有标头,您可能遗漏了什么,也许是文件名导致数据库查询失败。

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

【讨论】:

  • 谢谢@Nicole,我终于设法解决了这个问题。我通过标签获取电子邮件的值,甚至在 PHP 上打印值也向我返回了正确的值......但在 SQL qry 中是一个空字符串(我不明白为什么)。如果我在 XAML 中放置一个不可见的条目而不是标签,那么所有这些都有效...
  • @Jason 这是我在 PHP 中执行 QRY 的函数: public function updateImage ($ img, $ email) { $ stmt = $ this-> conn-> prepare ("UPDATE User SET image =?WHERE 电子邮件 =?"); $ stmt-> bind_param ("ss", $ img, $ email); $result = $stmt->execute(); $stmt->close();如果($结果){返回真; } 否则 { 返回假; } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 2023-04-02
  • 2021-07-27
  • 2016-11-30
相关资源
最近更新 更多