如何使用Httpclient上传图片?

时间:2019-06-27 11:14:32

标签: xamarin.forms

我想使用HttpClient上传图像。

在开发人员工具中,我找到了发送数据。

    ------WebKitFormBoundary6wotBLDvUeB8hNlv
Content-Disposition: form-data; name="upload"; filename="icons8-settings-26 (1).png"
Content-Type: image/png


------WebKitFormBoundary6wotBLDvUeB8hNlv--

我可以使用Byte Stream而不是MultipartFormDataContent发送数据吗?像HttpWebRequest吗?

如果我使用MultipartFormDataContent,将导致错误。

2 个答案:

答案 0 :(得分:0)

这是使用MultipartFormData上传图像的示例代码

private async void UploadImage()
    {
        //variable
                var url = "https://yoururl.com";
            var file = "path/to/file.png";

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

                    //create new HttpClient and MultipartFormDataContent
                    HttpClient client = new HttpClient();
                    MultipartFormDataContent content = new MultipartFormDataContent();
                    //byteArray Image
                    ByteArrayContent baContent = new ByteArrayContent(upfilebytes);

                    content.Add(baContent, "File", "filename.png");


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

答案 1 :(得分:0)

@daotin,如果您想以base64string的形式上传字节数组而不使用多部分,则可以尝试这样

    private void Upload()
    {
        string contents = Convert.ToBase64String(data);// here data is byte[] of your image
        UploadAttachment(contents);
    }

    public async Task<Tuple<bool, string>> UploadAttachment(string payload)
    {
        bool isSuccess = false;
        string message = string.Empty;

        Uri uri = new Uri(API_URL);
        try
        {
            HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
            var response = string.Empty;
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage result = null;
                result = await client.PostAsync(uri, content);

                if (result.IsSuccessStatusCode)
                    isSuccess = true;
                else
                {
                    var error = await result.Content.ReadAsStringAsync();
                    var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(error);
                    message = errorResponse?.Errors?.FirstOrDefault();
                }
            }
        }
        catch (Exception ex)
        {
            message = ex.Message;
        }
        return new Tuple<bool, string>(isSuccess, message);
    }