0

I want to using HttpClient to upload an Image.

In the developper tools I find the sending data.

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


------WebKitFormBoundary6wotBLDvUeB8hNlv--

Can I sending the data with Byte Stream not the MultipartFormDataContent?like HttpWebRequest?

If I using the MultipartFormDataContent it will cause an error.

user666
  • 329
  • 1
  • 7
  • 22
  • What error did you get? – nevermore Jun 28 '19 at 02:56
  • please see this https://stackoverflow.com/questions/56800269/how-to-set-the-content-type-of-httpclient – user666 Jun 28 '19 at 05:04
  • Can you try `request.Content.Headers.ContentType.MediaType = "multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";` or `request.Content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN");`. – nevermore Jun 28 '19 at 05:56
  • it will cause an error ,I can not set it, if I set the boundary there will be an error – user666 Jun 28 '19 at 07:45
  • What error? one of the identified items was in an invalid format? – nevermore Jul 01 '19 at 09:21

2 Answers2

0

This is a sample code to upload an image with 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;
                }
    }
Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45
0

@daotin, you can try like this if you want to upload byte array in the form of base64string without using multipart,

    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);
    }
KiShOrE
  • 933
  • 8
  • 25