C# 使用WCF服务和Xamarin.Forms将图像存储到服务器

C# 使用WCF服务和Xamarin.Forms将图像存储到服务器,c#,wcf,xamarin,xamarin.forms,C#,Wcf,Xamarin,Xamarin.forms,我正在使用Xamarin表单开发一个移动应用程序,在应用程序中将图像发送到服务器。为了发送图像,我们使用了WCF服务 下面是Xamarin应用程序的代码 using (var memoryStream = new MemoryStream()) { pick.GetStream().CopyTo(memoryStream); pick.Dispose(); byte[] byteImageArray = me

我正在使用Xamarin表单开发一个移动应用程序,在应用程序中将图像发送到服务器。为了发送图像,我们使用了WCF服务

下面是Xamarin应用程序的代码

using (var memoryStream = new MemoryStream())
        {
            pick.GetStream().CopyTo(memoryStream);
            pick.Dispose();
            byte[] byteImageArray = memoryStream.ToArray();
            try
            {
                var imageStream = new ByteArrayContent(byteImageArray);
                var multi = new MultipartContent();
                multi.Add(imageStream);

                var client = new HttpClient();
                var result = client.PostAsync("http://www.test.com/Services/Service.svc/SaveImage", multi).Result;

                var json = await result.Content.ReadAsStringAsync();
                var strNo = JsonConvert.DeserializeObject<string>(json);

            }
            catch (Exception ex)
            {
                await DisplayAlert("Error", ex.Message, "Ok");
            }
        }
现在有了这段代码,图像被成功地转换并存储在数据库blob中。 我面临的问题是,每当我将blob转换回图像时,图像就会被破坏。使用asp.net应用程序将图像插入blob时,blob的数据长度显示为18901,而使用移动应用程序插入相同图像时,数据长度显示为18987。 请帮助我解决数据长度问题,或者请指导使用WCF和Xamarin表单将图像存储到数据库中的更简单方法。

只需更改即可

var multi = new MultipartContent();
multi.Add(imageStream);


解决了这个问题。希望我不会在任何地方出错

例如,创建一个名为
PicturesController
的WebAPI。您必须使用
PUT
动词

/// <summary>
/// Receiving an image across WebAPI
/// </summary>
/// <returns></returns>
[HttpPut]
public HttpResponseMessage Put()
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);

    if (Request.Content.IsMimeMultipartContent())
    {
        try
        {
            Request.Content.LoadIntoBufferAsync().Wait();
            Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(
                new MultipartMemoryStreamProvider()).ContinueWith((task) => {
                MultipartMemoryStreamProvider provider = task.Result;
                foreach (HttpContent content in provider.Contents)
                {
                    Stream stream = content.ReadAsStreamAsync().Result;
                    Image image = Image.FromStream(stream);

                    try
                    {
                        string filename = string.Format("{0}{1}{2}{3}", 
                                                        DateTime.Now.Year, 
                                                        DateTime.Now.Month, 
                                                        DateTime.Now.Day, 
                                                        DateTime.Now.Second) + ".jpg";
                        foreach (var h in content.Headers.ContentDisposition.Parameters)
                        {
                            if (h.Name.ToLower() == "filename")
                            {
                                filename = h.Value.Replace("\\", "/").Replace("\"", "");
                                var pos = filename.LastIndexOf("/");
                                if (pos >= 0)
                                {
                                    filename = filename.Substring(pos + 1);
                                }
                                break;
                            }
                        }

                        string filePath = ConfigurationManager.AppSettings["Pictures"]
                                                              .ToString();
                        string fullPath = Path.Combine(filePath, filename);

                        EncoderParameters encparams = new EncoderParameters(1);
                        encparams.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
                        ImageCodecInfo ici = null;
                        foreach (ImageCodecInfo codec in ImageCodecInfo
                                                         .GetImageEncoders())
                        {
                            if (codec.MimeType == "image/jpeg")
                            {
                                ici = codec;
                                break;
                            }
                        }

                        image.JpegOrientation().Save(fullPath, ici, encparams);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            });
        }
        catch (Exception ex)
        {
            result.StatusCode = HttpStatusCode.InternalServerError;
        }

        return result;
    }
    else
    {
        throw new HttpResponseException(Request.CreateResponse(
                                        HttpStatusCode.NotAcceptable, 
                                        "This request is not properly formatted"));
    }
}
记住包括

using System.Net.Http;
using System.Net.Http.Headers;

我在很多应用程序中使用了这个实现,它工作得非常好。如果您有任何改进建议,请告诉我。

您能使用
WebAPI
吗?如果是,我有解决办法。@Enrico:是的,这是可能的。请引导
/// <summary>
/// Receiving an image across WebAPI
/// </summary>
/// <returns></returns>
[HttpPut]
public HttpResponseMessage Put()
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);

    if (Request.Content.IsMimeMultipartContent())
    {
        try
        {
            Request.Content.LoadIntoBufferAsync().Wait();
            Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(
                new MultipartMemoryStreamProvider()).ContinueWith((task) => {
                MultipartMemoryStreamProvider provider = task.Result;
                foreach (HttpContent content in provider.Contents)
                {
                    Stream stream = content.ReadAsStreamAsync().Result;
                    Image image = Image.FromStream(stream);

                    try
                    {
                        string filename = string.Format("{0}{1}{2}{3}", 
                                                        DateTime.Now.Year, 
                                                        DateTime.Now.Month, 
                                                        DateTime.Now.Day, 
                                                        DateTime.Now.Second) + ".jpg";
                        foreach (var h in content.Headers.ContentDisposition.Parameters)
                        {
                            if (h.Name.ToLower() == "filename")
                            {
                                filename = h.Value.Replace("\\", "/").Replace("\"", "");
                                var pos = filename.LastIndexOf("/");
                                if (pos >= 0)
                                {
                                    filename = filename.Substring(pos + 1);
                                }
                                break;
                            }
                        }

                        string filePath = ConfigurationManager.AppSettings["Pictures"]
                                                              .ToString();
                        string fullPath = Path.Combine(filePath, filename);

                        EncoderParameters encparams = new EncoderParameters(1);
                        encparams.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
                        ImageCodecInfo ici = null;
                        foreach (ImageCodecInfo codec in ImageCodecInfo
                                                         .GetImageEncoders())
                        {
                            if (codec.MimeType == "image/jpeg")
                            {
                                ici = codec;
                                break;
                            }
                        }

                        image.JpegOrientation().Save(fullPath, ici, encparams);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            });
        }
        catch (Exception ex)
        {
            result.StatusCode = HttpStatusCode.InternalServerError;
        }

        return result;
    }
    else
    {
        throw new HttpResponseException(Request.CreateResponse(
                                        HttpStatusCode.NotAcceptable, 
                                        "This request is not properly formatted"));
    }
}
/// <summary>
/// Uploads the photo.
/// </summary>
/// <returns>The photo.</returns>
/// <param name="photoBytes">Photo bytes.</param>
public async Task<bool> UploadPhoto(byte[] photoBytes, int PropertyId, string fileName)
{
    bool rtn = false;

    var content = new MultipartFormDataContent();
    var fileContent = new ByteArrayContent(photoBytes);
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    fileContent.Headers.ContentDisposition = 
                         new ContentDispositionHeaderValue("attachment") {
        FileName = fileName + ".jpg"
    };
    content.Add(fileContent);
    fileContent.Headers.ContentDisposition.Parameters.Add(
                         new NameValueHeaderValue("<otherParam>", "<otherParamValue>"));

    string url = RestURL() + "Pictures/Put";
    try
    {
        using (var client = new HttpClient())
        {
            // add an authotization token if you have one
            //client.DefaultRequestHeaders.Add("authenticationToken", "yourToken");
            await client.PutAsync(url, content);
            rtn = true;
        }
    }
    catch (Exception ex)
    {
    }

    return rtn;
}
using System.Net.Http;
using System.Net.Http.Headers;