'Upload Image using Multipart Form
I have a "choose" button to select an image from the device using FileOpenPicker and a "jawab" button to upload the image to the server using a multipart form
Code:
private Stream stream = new MemoryStream();
private async void chooseBtn_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
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 jawabBtn_Click(object sender, RoutedEventArgs e)
{
Uri urlPath = new Uri("..../essay/test");
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization",
string.Format("Bearer {0}", tkn));
HttpMultipartFormDataContent values = new HttpMultipartFormDataContent();
values.Add(new HttpStringContent(textValue), "answer");
values.Add(new HttpStringContent(((App)(App.Current)).SessionID.ToString()), "session");
values.Add(new HttpStringContent(examstep), "step");
values.Add(new HttpStringContent(questionId), "question");
values.Add(new HttpStreamContent(stream.AsInputStream()), "image");
var response = new HttpResponseMessage();
try
{
response = await httpClient.PostAsync(urlPath, values);
}
catch (Exception ex)
{
MessageDialog messageDialog = new MessageDialog(ex.ToString(), "Server Error");
messageDialog.Commands.Add(new UICommand("OK", (command) =>
{
this.Frame.GoBack();
}));
await messageDialog.ShowAsync();
}
}
I'm having problem like below image when uploading image to server
How to handle it?
Solution 1:[1]
I've made a simple test about this. Please try to use the IRandomAccessStream directly for your HttpStreamContent. In this way, my code doesn't throw any exception.
Like this:
fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);
//... other codes
HttpClient httpClient = new HttpClient();
HttpMultipartFormDataContent values = new HttpMultipartFormDataContent();
//....other codes
values.Add(new HttpStreamContent(fileStream), "image");
var response = new HttpResponseMessage();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roy Li - MSFT |
