简体   繁体   中英

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

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);



    }

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

You can use HttpStreamContent class to upload stream directly to your web server. For example:

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

private async void SelectImage(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 UploadImage(object sender, RoutedEventArgs e)
{
    Uri uri = new Uri("you web uri");
    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);
}

As we've discussed in your another question, you may refer to the official HttpClient sample , scenario 5 is about posting stream.

For a client app, what we can do is just uploading the file stream correctly, and the important thing is, you will need to implement the image decoding function and save to mysql in your server.

By the way, you've asked the same question upload an image into mysql database using windows universal app once and I've seen your newest comment to my answer, I won't update my answer in that case, hope this is the right you asked for.

@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 = "" };
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM