簡體   English   中英

使用 HttpClient 上傳圖片

[英]Upload image using HttpClient

我想使用 HttpClient 將文件上傳到 php 腳本,以將其保存在 Windows Phone 8.1 應用程序中的服務器上。

這是我從這篇文章中得到的 C# 代碼。

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;

     }
}

並使用此代碼檢索 php 腳本中的數據

<?
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");
?>

但是我總是得到的結果是“找不到數據”,盡管有一個圖像文件。 將它作為 POST 參數傳遞是不是我做錯了什么?

好吧,經過數小時的研究,我得出了應該從草稿重新開始的觀點。 我使用以下 C# 代碼模擬 Html 表單上傳:

  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;
        }

我接收數據的 php 文件如下所示:

<?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.\n";
} else {
    echo "Possible file upload attack!\n";
}

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

現在它可以正常工作了,我希望有人可以重用我的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM