how to use httpClient.postAsync to upload an image or bytes[] in UWP

Viewed 9268

so i need to upload an image into my Mysql databse along with some other strings like name for an example ... i was able to add the name into Mysql DB but i can not do it for the image . I converted the image inti an byte [] and i'm stuck now .. here is the code i used

private Stream stream = new MemoryStream();
    private CancellationTokenSource cts;

    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void buttonUpload_Click(object sender, RoutedEventArgs e)
    {
        FileOpenPicker open = new FileOpenPicker();
        open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        open.ViewMode = PickerViewMode.Thumbnail;

        // Filter to include a sample subset of file types
        open.FileTypeFilter.Clear();
        open.FileTypeFilter.Add(".bmp");
        open.FileTypeFilter.Add(".png");
        open.FileTypeFilter.Add(".jpeg");
        open.FileTypeFilter.Add(".jpg");

        // Open a stream for the selected file
        StorageFile file = await open.PickSingleFileAsync();

        // Ensure a file was selected
        if (file != null)
        {
            // Ensure the stream is disposed once the image is loaded
            using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);
                fileStream.AsStream().CopyTo(stream);
                img.Source = bitmapImage;
            }
        }
    }

    private async void submit_Click(object sender, RoutedEventArgs e)
    {


        Uri uri = new Uri("http://localhost/mydatabase/add.php");
        HttpClient client = new HttpClient();
        HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri);
        request.Content = streamContent;
        HttpResponseMessage response = await client.PostAsync(uri, streamContent).AsTask(cts.Token);



    }
3 Answers

Try this its working for me:

private static async Task Upload(string actionUrl)
{
    Image newImage = Image.FromFile(@"Absolute Path of image");
    ImageConverter _imageConverter = new ImageConverter();
    byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));

    var formContent = new MultipartFormDataContent
    {
        //send form text values here
        {new StringContent("value1"), "key1"},
        {new StringContent("value2"), "key2" },
        // send Image Here
        {new StreamContent(new MemoryStream(paramFileStream)), "imagekey", "filename.jpg"}
    };

    var myHttpClient = new HttpClient();
    var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
    string stringContent = await response.Content.ReadAsStringAsync();

    return response;
}

@semwal

I can't recall specifically what was the actual fix but here is my solution. Hope it helps

   public async Task<JsonApiResult> SendHttpData(string file, string token, string claimid, string serviceMethod)
    {
        serviceMethod = $"{serviceMethod}/?claimid={claimid}&token={token}";

        HttpClient _httpClient = new HttpClient();

        _httpClient.Timeout = TimeSpan.FromMinutes(10);

        _httpClient.BaseAddress = new Uri(_url);

        try
        {
            string filename = Path.GetFileName(file);

            MultipartFormDataContent content = new MultipartFormDataContent();

            var fileContent = new StreamContent(File.OpenRead(file));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "result", FileName = $"\"{filename}\"" };
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");

            content.Add(fileContent);

            HttpResponseMessage response = await _httpClient.PostAsync(serviceMethod, content);

            if (response.IsSuccessStatusCode)
            {
                return new JsonApiResult { Result = "success", Message = "File Sent", Data = "" };
            }
            else
            {
                return new JsonApiResult { Result = "fail", Message = response.ToString(), Data = "" };
            }
        }
        catch (Exception e)
        {
            return new JsonApiResult { Result = "fail", Message = e.Message, Data = "" };
        }
    }
}
Related