Window Phone 8提交带有图像的帖子表单

本文关键字:表单 图像 Phone 提交 Window | 更新日期: 2023-09-27 18:25:53

我正在使用window phone 8.0,在尝试从手机向网站提交帖子请求时遇到问题。输入名为"file",它只接受图像文件。

<form action="upmeme" method="post" enctype="multipart/form-data">
   <input type="file" class="file" name="file" id="file"><br>
   <input type="submit" class="submit" name="submit" value="Submit">
</form>

或者您可以访问此处:此网站

我使用PhotoPicker从库中选择照片,并将其保存到"照片"Stream photo = e.ChosenPhoto;中,效果非常好。

现在我需要上传照片并提交上面的表格。这是我调用的代码,用于发送帖子请求,但它不起作用,响应与提交之前相同

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

我试着在网上查找,结果和我的一样。我的代码哪里错了吗?

Window Phone 8提交带有图像的帖子表单

检索位图图像:

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

创建文件流:

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

从图像创建内存流:

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