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


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

所以我需要将图像与其他一些字符串(例如名称)一起上传到我的Mysql databse中...我能够将名称添加到Mysql DB中,但是我无法为图像执行此操作。我转换了图像inti一个字节[],我现在被困住了..这是我使用的代码

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

    }

试试这个它对我有用:

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;
}
您可以使用

HttpStreamContent 类将流直接上传到您的 Web 服务器。例如:

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

正如我们在您的另一个问题中所讨论的,您可以参考官方 HttpClient 示例,场景 5 是关于发布流的。

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

顺便说一句,您曾经问过同样的问题,使用 Windows 通用应用程序将图像上传到 mysql 数据库,我看到了您对我的答案的最新评论,在这种情况下我不会更新我的答案,希望这是您要求的权利。

@semwal

我不记得具体是什么实际的修复程序,但这是我的解决方案。希望对你有帮助

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