【问题标题】:Xamarin Forms Upload image and variable to webpageXamarin Forms 将图像和变量上传到网页
【发布时间】:2020-01-02 06:22:42
【问题描述】:

我有问题。我想将图像和变量上传到我的网页,所以我创建了以下代码:

using (var formContent = new MultipartFormDataContent("NKdKd9Yk"))
{
    formContent.Headers.ContentType.MediaType = "multipart/form-data";

    StringContent UserIdContent = new StringContent(App.User.Id.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
    formContent.Add(UserIdContent, "id");

    StringContent CreatedImageContent = new StringContent(CreatedImage, Encoding.UTF8, "binary/octet-streOpenWriteam");
    formContent.Add(CreatedImageContent , "image");

    using (var client = new HttpClient())
    {
        try
        {
            // 4.. Execute the MultipartPostMethod
            var message = await client.PostAsync(url, formContent);
            // 5.a Receive the response
            var result = await message.Content.ReadAsStringAsync();

            if (result == "Success")
            {
                App.Current.MainPage = new SideMenuItems();
            }
        }
        catch (Exception ex)
        {
            // Do what you want if it fails.
            throw ex;
        }
    }
}

现在这两个变量都被服务器接收了,但 image 变量是设备上图像的路径,而不是图像本身。

我做错了什么?

【问题讨论】:

    标签: c# xamarin xamarin.forms xamarin.android xamarin.ios


    【解决方案1】:

    使用路径获取图片流,使用流内容。

    using (var formContent = new MultipartFormDataContent("NKdKd9Yk")) {
        formContent.Headers.ContentType.MediaType = "multipart/form-data";
    
        var id = App.User.Id.ToString();
        StringContent UserIdContent = new StringContent(id, Encoding.UTF8, "application/x-www-form-urlencoded");
        formContent.Add(UserIdContent, "id");
    
        FileStream fs = System.IO.File.OpenRead(CreatedImage);
        formContent.Add(new StreamContent(fs), "image");
    
        using (var client = new HttpClient()) {
            try {
                // 4.. Execute the MultipartPostMethod
                var message = await client.PostAsync(url, formContent);
                // 5.a Receive the response
                var result = await message.Content.ReadAsStringAsync();
    
                if (result == "Success") {
                    App.Current.MainPage = new SideMenuItems();
                }
            } catch (Exception ex) {
                // Do what you want if it fails.
                throw ex;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-19
      • 2020-09-16
      • 2017-07-26
      • 2020-08-05
      • 2017-12-14
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多