Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

c# - Upload image using HttpClient

I want to upload a file using HttpClient to a php script to save it on a server in a Windows Phone 8.1 application.

Here is my C# code I got from this post.

private async Task<string> GetRawDataFromServer(byte[] data)
{
    //Debug.WriteLine("byte[] data length:" + Convert.ToBase64String(data).Length);
    var requestContent = new MultipartFormDataContent();
    //    here you can specify boundary if you need---^
    var imageContent = new ByteArrayContent(data);
    imageContent.Headers.ContentType =
        MediaTypeHeaderValue.Parse("image/jpeg");

    requestContent.Add(imageContent, "image", "image.jpg");
    using (var client = new HttpClient())
     {

         client.BaseAddress = new Uri("http://www.x.net/");

        var result = client.PostAsync("test/fileupload.php", requestContent).Result;

         return result.Content.ReadAsStringAsync().Result;

     }
}

And with this code I retrieve the data in the php script

<?
function base64_to_image( $imageData, $outputfile ) {
    /* encode & write data (binary) */
    $ifp = fopen( $outputfile, "wb" );
    fwrite( $ifp, base64_decode( $imageData ) );
    fclose( $ifp );
    /* return output filename */
    return( $outputfile );
}       

if (isset($_POST['image'])) {
    base64_to_jpeg($_POST['image'], "image.jpg");
}
else
    die("no image data found");
?>

But the result I always get is "No Data found" although there IS an image file. Am I doing something wrong passing it as a POST parameter?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Okay after hours of researching I came to the point that I should restart from draft. I simulate a Html form upload with following C# code:

  private async Task<string> UploadImage(StorageFile file)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://your.url.com/");
            MultipartFormDataContent form = new MultipartFormDataContent();
            HttpContent content = new StringContent("fileToUpload");
            form.Add(content, "fileToUpload");
            var stream = await file.OpenStreamForReadAsync();
            content = new StreamContent(stream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileToUpload",
                FileName = file.Name
            };
            form.Add(content);
            var response = await client.PostAsync("upload.php", form);
            return response.Content.ReadAsStringAsync().Result;
        }

And my php file to receive the data looks as the follwing:

<?php 
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.
";
} else {
    echo "Possible file upload attack!
";
}

echo 'Here is some more debugging info:';
print_r($_FILES);
?>

Now it works as it should and I hope somebody can reuse my code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...