如何使用httpClient.postAsync在UWP中上传图像或字节[]

时间:2016-03-13 23:45:16

标签: c# php mysql image win-universal-app

所以我需要将一个图像上传到我的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);



    }

3 个答案:

答案 0 :(得分:1)

您可以使用HttpStreamContent class将流直接上传到您的网络服务器。例如:

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 sample,方案5是关于发布流。

对于客户端应用,我们可以做的只是正确上传文件流,重要的是,您需要实现图像解码功能并保存到服务器中的mysql。

顺便说一句,你曾经问过同一个问题upload an image into mysql database using windows universal app,而且我已经看到了你对我的回答的最新评论,在那种情况下我不会更新我的答案,希望这是你要求的权利。

答案 1 :(得分:1)

尝试一下对我有用:

私有静态异步任务上传(字符串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();

返回响应;     }

答案 2 :(得分:0)

@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 = "" };
        }
    }
}