gpt4 book ai didi

c# - 如何使用 httpClient.postAsync 在 UWP 中上传图像或 bytes[]

转载 作者:行者123 更新时间:2023-12-05 01:20:01 25 4
gpt4 key购买 nike

所以我需要上传一张图片到我的 Mysql 数据库以及一些其他字符串,例如名称......我能够将名称添加到 Mysql 数据库中,但我无法为图像添加名称。我将图像转换为一个字节 [],现在我卡住了..这是我使用的代码

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

关于c# - 如何使用 httpClient.postAsync 在 UWP 中上传图像或 bytes[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35977363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com