Window Phone 8 submit post form with an image
我正在使用Window Phone 8.0,尝试将手机的发帖请求提交到网站时遇到问题。输入名为" file",它仅接受图像文件。
1 2 3 4 | <form action="upmeme" method="post" enctype="multipart/form-data"> <input type="file" class="file" name="file" id="file"> <input type="submit" class="submit" name="submit" value="Submit"> </form> |
或者您可以在这里访问:此网站
我使用PhotoPicker从库中选择了照片,并将其保存为"照片"
现在我需要上传照片并提交上面的表格。这是我的代码,用于发送发帖请求,但它不起作用,响应与登顶之前的相同
1 2 3 4 5 6 7 8 | photo.Position = 0; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(url); HttpRequestMessage request = new HttpRequestMessage(); MultipartFormDataContent form = new MultipartFormDataContent(); form.Add(new StreamContent(photo),"file"); HttpResponseMessage response = await client.PostAsync(url, form); string responseBodyAsText = await response.Content.ReadAsStringAsync(); |
我试图查看Internet周围的内容,结果与我的发现相同。我的代码在某处出错吗?
检索位图图像:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args) { if (args.Files.Count > 0) { var imageFile = args.Files[0] as StorageFile; // Ensure the stream is disposed once the image is loaded using (IRandomAccessStream fileStream = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read)) { // Set the image source to the selected bitmap BitmapImage bitmapImage = new BitmapImage(); await bitmapImage.SetSourceAsync(fileStream); ImageControl.Source = bitmapImage; await _viewModel.Upload(imageFile); } } } |
创建文件流:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | internal async Task Upload(Windows.Storage.StorageFile file) { var fileStream = await file.OpenAsync(FileAccessMode.Read); fileStream.Seek(0); var reader = new Windows.Storage.Streams.DataReader(fileStream.GetInputStreamAt(0)); await reader.LoadAsync((uint)fileStream.Size); Globals.MemberId = ApplicationData.Current.LocalSettings.Values[Globals.PROFILE_KEY]; var userName ="Rico"; var sex = 1; var url = string.Format("{0}{1}?memberid={2}&name={3}&sex={4}", Globals.URL_PREFIX,"api/Images", Globals.MemberId, userName,sex); byte[] image = new byte[fileStream.Size]; await UploadImage(image, url); } |
从图像创建内存流:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public async Task UploadImage(byte[] image, string url) { Stream stream = new System.IO.MemoryStream(image); HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream()); Uri resourceAddress = null; Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress); Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress); request.Content = streamContent; var httpClient = new Windows.Web.Http.HttpClient(); var cts = new CancellationTokenSource(); Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token); } |