Thursday, April 30, 2015

[WP8.1][C#]Why when I try to upload an Image with Windows Phone it uploads a random thing?

I'm trying to upload an image from my Windows Store App (Windows Phone 8.1) to hosting (using PHP) but always when I "uploaded" the image, and I check its result the "image" it's a corrupted file. I think it's related to the byte array conversion but I haven't found another way to do it. This is my code:

C# Code:

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

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

        public async Task<string> Upload()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    using (var content =
                        new MultipartFormDataContent())
                    {
                        byte[] data = ConvertBitmapToByteArray();
                        content.Add(new StreamContent(new MemoryStream(data)), "userfile", fileNewImage);

                        using (
                           var message =
                               await client.PostAsync("http://ift.tt/1KwegGL;, content))
                        {
                            var input = await message.Content.ReadAsStringAsync();

                            return input;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
        }

PHP code:

<?php
        header('Content-Type: application/json');
        $uploaddir = getcwd();
        $uploadfile = $uploaddir . "/" . basename($_FILES['userfile']['name']);

        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
                echo '{"result": "sucessfull"}';
        } else {
           echo '{"result": "-1"}';
        }?>

I wish someone could give me an idea about what I my mistake and how to fix it. Thanks in advance for your worthy knowledge.

Federico Navarrete


No comments:

Post a Comment