简体   繁体   English

如何在 UWP 中使用 httpClient.postAsync 上传图像或字节 []

[英]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 .所以我需要将图像与其他一些字符串(如名称)一起上传到我的 Mysql 数据库中,例如……我能够将名称添加到 Mysql DB 中,但我无法为图像执行此操作。 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.您可以使用HttpStreamContent 类将流直接上传到您的 Web 服务器。 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.正如我们在您的另一个问题中所讨论的,您可以参考官方的HttpClient 示例,场景 5 是关于发布流的。

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.对于客户端应用程序,我们能做的只是正确上传文件流,重要的是,您需要实现图像解码功能并保存到服务器中的mysql。

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.顺便说一句,你曾经问过同样的问题, 使用 windows 通用应用程序将图像上传到 mysql 数据库,我已经看到你对我的答案的最新评论,在这种情况下我不会更新我的答案,希望这是正确的你问的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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