文件转换为字节数组不正确

时间:2017-01-08 21:27:28

标签: c# php arrays image xamarin

我正在尝试从设备库中选择一个图像并将其上传到远程服务器,将图像转换为字节数组并使用php脚本发送它。

上传脚本似乎有效,因为该文件出现在服务器目录中,但是当我打开页面时返回一个错误,例如“无法打开图像,因为它包含错误”。

MyPage.xaml.cs

public MyPage()
    {
        InitializeComponent();

        pickPhoto.Clicked += async (sender, args) =>
        {
            if (!CrossMedia.Current.IsPickPhotoSupported)
            {
                await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
                return;
            }
            var file = await CrossMedia.Current.PickPhotoAsync();

            if (file == null)
                return;

            image.Source = ImageSource.FromStream(() =>
              {
                  var stream = file.GetStream();
                  return stream;
              });

            //ADD THIS
            var httpClient = new HttpClient();
            await httpClient.PostAsync("http://mysite.altervista.org/path/upload_file.php?image=", new StreamContent(file.GetStream()));//I tried also without ?image= 

            //byte[] abyte = ByteArrayFromFile(file_tmp.GetStream());
            //await sendImage(abyte);
        };
    }

    public async Task<HttpResponseMessage> sendImage(byte[] byteArray)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("http://mysite.altervista.org/");
        StringContent str = new StringContent("image="+byteArray.GetValue(), Encoding.UTF8, "application/x-www-form-urlencoded");
        var response = await client.PostAsync(new Uri("http://mysite/upload_file.php"), str);
        var placesJson = response.Content.ReadAsStringAsync().Result;
        System.Diagnostics.Debug.WriteLine("RESPONSE: " + placesJson);
        return response;
    }

    public static byte[] ByteArrayFromFile(Stream location)
    {
        using (var streamReader = new StreamReader(location))
        {
            var bytes = default(byte[]);
            using (var memstream = new MemoryStream())
            {
                streamReader.BaseStream.CopyTo(memstream);
                bytes = memstream.ToArray();
                return bytes;
            }
        }
    }

upload_file.php

<?php
    $base=$_REQUEST['image'];
    $filename = "myimg.jpg";
    //$binary=base64_decode($base); //commented this
    header('Content-Type: bitmap; charset=utf-8');
    $file = fopen($filename, 'wb');
    fwrite($file, $base); //changed $binary to $base
    fclose($file);
    echo 'Image upload complete, Please check your php file directory';
?>

1 个答案:

答案 0 :(得分:0)

使用GET请求发送文件不是解决此问题的方法。

请改用:

 httpClient.PostAsync("url.com", new StreamContent(stream));