[英]how to use httpClient.postAsync to upload an image or bytes[] in UWP
所以我需要將圖像與其他一些字符串(如名稱)一起上傳到我的 Mysql 數據庫中,例如……我能夠將名稱添加到 Mysql DB 中,但我無法為圖像執行此操作。 我將圖像轉換為一個字節 [] 並且我現在卡住了..這是我使用的代碼
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 = "" };
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.