发送图像的WebAPI服务 [英] Send image to WebApi service

查看:149
本文介绍了发送图像的WebAPI服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做Windows Phone上的一个项目,用户可以拍摄照片,将它保存在手机和明年上传我的服务器上。因此,有两个项目,WP8.1和ASP.NET Web API。

目前我不知道如何上传照片到我的服务器(从手机),我甚至不知道如何捕捉它的API。什么是让它的最佳方式?

下面是我的方法显示在屏幕上(电话),其采取的用户的照片上。

 专用异步无效LoadCapturedphoto(字符串文件名)
    {
        //加载保存的图像
        StorageFolder pictureLibrary = KnownFolders.SavedPictures;
        StorageFile savedPicture =等待pictureLibrary.GetFileAsync(文件名);
        ImageProperties imgProp =等待savedPicture.Properties.GetImagePropertiesAsync();
        VAR savedPictureStream =等待savedPicture.OpenAsync(FileAccessMode.Read);        //设置图片属性并显示拍摄的照片
        位图=新的WriteableBitmap的((INT)imgProp.Width,(INT)imgProp.Height);
        等待bitmap.SetSourceAsync(savedPictureStream);
        takenImage.Source =位图;
        takenImage.Visibility = Visibility.Visible;    }

我想我应该转换为WriteableBitmap的字节型[],发送这些字节]通过API服务器和服务器转换字节[]为JPG / PNG /等。

 专用字节[] ConvertBitmapToByteArray(WriteableBitmap的位图)
    {
        WriteableBitmap的BMP位图=;        使用(流流= bmp.PixelBuffer.AsStream())
        {
            MemoryStream的MemoryStream的=新的MemoryStream();
            stream.CopyTo(MemoryStream的);
            返回memoryStream.ToArray();
        }
    }

任何想法?你觉得这是好主意,使它像吗? WriteableBitmap的 - >字节[]和服务器上的下一个字节[] - > JPG / PNG等它甚至有可能

如果这是可以做到更容易请写出一些样品。

这是我的方法调用API的方法

 公共字符串apiCommand(串API,JSON字符串)
    {
        使用(VAR的HttpClient =新的HttpClient())
        {
            HttpContent内容=新的StringContent(JSON,Encoding.UTF8);
            content.Headers.ContentType =新MediaTypeHeaderValue(应用/ JSON);            HTT presponseMessage响应= httpClient.PostAsync(Variables.apiURL + API,内容)。结果;
            response.EnsureSuccessStatus code();            任务<串GT; responseBody = response.Content.ReadAsStringAsync();
            //变种味精=新MessageDialog(responseBody.Result.ToString());            如果(response.Status code.ToString()!=OK)
            {
                返回error:+ response.Status code.ToString();
            }
            其他
            {
                返回SUCCES:+ responseBody.Result.ToString();
            }
        }
    }


解决方案

您需要多部分使用/ form-data的请求到服务器。您可以使用有效载荷领域的JSON发送到Web API(另一种选择是单独发送每一个领域,但你需要思考这样做。)

这或许可以帮助你:

 公共字符串UploadUserPictureApiCommand(串API,JSON字符串,字节[]图片)
{
    使用(VAR的HttpClient =新的HttpClient())
    {       MultipartFormDataContent形式=新MultipartFormDataContent();       form.Add(新的StringContent(JSON),有效载荷);
       form.Add(新ByteArrayContent(图片,0,picture.Count()),user_picture,user_picture.jpg);       HTT presponseMessage响应=等待httpClient.PostAsync(API,形式);       response.EnsureSuccessStatus code();       任务<串GT; responseBody = response.Content.ReadAsStringAsync();        如果(response.Status code.ToString()!=OK)
        {
            返回error:+ response.Status code.ToString();
        }
        其他
        {
            返回SUCCES:+ responseBody.Result.ToString();
        }
    }
}

I'm making a project on Windows Phone where user can take a photo, save it on phone and next upload on my server. So there are two projects, WP8.1 and ASP.NET WEB API.

Currently I don't know how to upload photo to my server(from phone), I even don't know how to catch it in API. What's the best way to make it?

Here is my method to show on the screen(phone), picture which was taken by user.

private async void LoadCapturedphoto(string filename)
    {
        //load saved image
        StorageFolder pictureLibrary = KnownFolders.SavedPictures;
        StorageFile savedPicture = await pictureLibrary.GetFileAsync(filename);
        ImageProperties imgProp = await savedPicture.Properties.GetImagePropertiesAsync();
        var savedPictureStream = await savedPicture.OpenAsync(FileAccessMode.Read);

        //set image properties and show the taken photo
        bitmap = new WriteableBitmap((int)imgProp.Width, (int)imgProp.Height);
        await bitmap.SetSourceAsync(savedPictureStream);
        takenImage.Source = bitmap;
        takenImage.Visibility = Visibility.Visible;

    }

I think that I should convert WriteableBitmap to Byte[], send these Byte[] by API to server and on server convert Byte[] to JPG/PNG/etc.

private byte[] ConvertBitmapToByteArray(WriteableBitmap bitmap)
    {
        WriteableBitmap bmp = bitmap;

        using (Stream stream = bmp.PixelBuffer.AsStream())
        {
            MemoryStream memoryStream = new MemoryStream();
            stream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }

Any ideas? Do you think it's good idea to make it like that? WriteableBitmap -> Byte[] and next on server Byte[] -> JPG/PNG etc. Is it even possible?

If it can be done much more easier please write some samples.

it's my method for calling api methods

public string apiCommand(string api, string json)
    {
        using (var httpClient = new HttpClient())
        {
            HttpContent content = new StringContent(json, Encoding.UTF8);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = httpClient.PostAsync(Variables.apiURL + api, content).Result;
            response.EnsureSuccessStatusCode();

            Task<string> responseBody = response.Content.ReadAsStringAsync();
            //var msg = new MessageDialog(responseBody.Result.ToString());

            if (response.StatusCode.ToString() != "OK")
            {
                return "ERROR: " + response.StatusCode.ToString();
            }
            else
            {
                return "SUCCES: " + responseBody.Result.ToString();
            }
        }
    }

解决方案

You need to use multipart/form-data request to the server. You can send the json to the web api using payload field (another alternative is send every field separately, but you need reflection to do that.)

This maybe can help you:

public string UploadUserPictureApiCommand(string api, string json, byte[] picture)
{
    using (var httpClient = new HttpClient())
    {

       MultipartFormDataContent form = new MultipartFormDataContent();

       form.Add(new StringContent(json), "payload");
       form.Add(new ByteArrayContent(picture, 0, picture.Count()), "user_picture", "user_picture.jpg");

       HttpResponseMessage response = await httpClient.PostAsync(api, form);

       response.EnsureSuccessStatusCode();

       Task<string> responseBody = response.Content.ReadAsStringAsync();

        if (response.StatusCode.ToString() != "OK")
        {
            return "ERROR: " + response.StatusCode.ToString();
        }
        else
        {
            return "SUCCES: " + responseBody.Result.ToString();
        }
    }
}

这篇关于发送图像的WebAPI服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆