php - 使用 REST 在 PHP 中上传文件

标签 php rest file-upload curl

有没有办法使用 PHP 使用 REST 将文件从客户端上传到服务器,

我正在尝试使用下面的代码,但它对我不起作用。

<?php

$file_to_upload = array('file_contents'=>'@c:\\test.txt');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/api/upload.php');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSER, TRUE);
curl_setopt($ch, CURLOPT_UPLOAD, TRUE);
curl_setopt($ch, CURLOPT_POST,TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $file_to_upload);
 curl_exec($ch) or die( curl_error($ch) );
$error = curl_error($ch);
curl_close ($ch);
echo " Server response: ".$result;
echo " Curl Error: ".$error;

?>

和我的 upload.php

$uploaddir = realpath('./') . '/';
$uploadfile = $uploaddir . basename($_POST['file']['name']);

echo $uploadfile;
echo "\n";
echo '<pre>';
echo $_POST['file']['tmp_name'];
       if (move_uploaded_file($_POST['file']['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);
       echo "\n<hr />\n";
       print_r($_POST);
print "</pr" . "e>\n";
?>

最佳答案

试试这个。

索引.php

<?php
    echo "<pre>";
    print_r($_FILES);
    error_reporting(9);
    if($_REQUEST['action'] == 'submit') {
        $ch = curl_init();
        $filePath = $_FILES['file_upl']['tmp_name'];
        $fileName = $_FILES['file_upl']['name'];
        $data = array('name' => 'Foo', 'file' => "@$filePath", 'fileName' =>$fileName);             
        curl_setopt($ch, CURLOPT_URL, 'http://www.restServiceHost.com/file3/upload.php');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_exec($ch);
        curl_close($ch);
    }
?>

<form name="file_up" action="" method="POST" enctype="multipart/form-data">
Upload your file here
<input type="file" name="file_upl" id="file_upl"/>
<input type="submit" name="action" value="submit"/>
</form>

和 upload.php 在 http://www.restServiceHost.com/file3

<?php
    echo "<pre>";
    echo 'in upload.php<br/>';
    print_r($_FILES);
    print_r($_REQUEST);
    move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_REQUEST["fileName"]);
?>

关于php - 使用 REST 在 PHP 中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776003/

相关文章:

java - 使用浏览器访问文件系统文件

javascript - 图像文件上传-无文件上传错误

php - AJAX POST 二维数组到 Zend Controller 并接收它

php - 使用 PHP 5.6 生成范围内的安全随机整数

php - 检测 url 是否从页面点击而不是在浏览器中复制粘贴的最佳选择

rest - 如何通过HBase REST服务获取Phoenix表数据

php - 如何下载上传的文件?

javascript - Angular 休息调用未定义响应对象属性

rest - 验证 OpenAPI 对 REST 设计最佳实践的合规性

jsf - 上传的图片仅在刷新页面后可用