0

I am making an app which can upload image to a server (the server works well), and I use this method to upload my image to it, but when I get the respond from the result, it return a null string, can you explain for me what did I do wrong.

I followed this method: How to upload file to server with HTTP POST multipart/form-data

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
byte[] bytes = await Converter.GetBytesAsync(storageFile);
form.Add(new ByteArrayContent(bytes, 0, bytes.Count()), "\"upload-file\"", "\"test.jpg\"");
HttpResponseMessage response = await httpClient.PostAsync("my-url", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
Debug.WriteLine("res: " + sd); // this return a null string

The request return like this:

--a81d2efe-5f2e-4f84-83b9-261329bee20b Content-Disposition: form-data; name="upload-file"; filename="test.jpg"; filename*=utf-8''%22test.jpg%22

����Ivg?�aEQ�.�����(��9%�=��>�C�~/�QG$�֨������(�`������QE��Z��

Can you help me please!

P/s: Here is my convert method

        public static async Task<byte[]> GetBytesAsync(StorageFile file)
        {
            byte[] fileBytes = null;
            if (file == null) return null;
            using (var stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (var reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(fileBytes);
                }
            }
            return fileBytes;
        }
Community
  • 1
  • 1
iamatsundere181
  • 1,289
  • 1
  • 14
  • 32

2 Answers2

0

This might help

 private async Task<string> UploadImage(StorageFile file)
            {
                HttpClient client = new HttpClient();
                MultipartFormDataContent form = new MultipartFormDataContent();
                HttpContent content = new StringContent("fileToUpload");
                form.Add(content, "fileToUpload");
                var stream = await file.OpenStreamForReadAsync();
                content = new StreamContent(stream);
                content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "fileToUpload",
                    FileName = file.Name
                };
                form.Add(content);
                var response = await client.PostAsync("my-url", form);
                return response.Content.ReadAsStringAsync().Result;
            }
Archana
  • 3,135
  • 1
  • 13
  • 21
0

Use ByteArrayContent instead of StringContent. That Should work. And if you are expecting a stream-response you should use ReadAsStreamAsync instaed of ReadAsStringAsync.

Chirag Shah
  • 971
  • 1
  • 6
  • 12