如何将带有curl的文件发送到控制器

时间:2012-07-20 11:13:41

标签: php cakephp curl

我有一个带图片的网址:http://www.example.com/image.jpg
我在控制器中有一个动作,通过用户输入将文件上传到服务器。我想使用相同的操作来通过url上传文件。我开始从图像中获取数据:

$url = "http://www.example.com/image.jpg";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);

现在如何将$ rawdata发送到控制器,以便像普通用户上传一样处理?

由于

1 个答案:

答案 0 :(得分:0)

我自己想出来了。

$url = "http://www.example.com/image.jpg";
$filename = basename($url, rand_string(7));
$path = realpath("../webroot/uploads/")."/".$filename;


$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec($ch);
curl_close ($ch);

if(file_exists($path)){
    unlink($path);
}

$file = fopen($path, 'x');

fwrite($file, $rawdata);
fclose($file);


$post_data['Filedata'] = '@'.$path;
$url = "http://localhost/controller/action";
$ch = curl_init();
// Set URL on which you want to post the Form and/or data
curl_setopt($ch, CURLOPT_URL, $url);
// Data+Files to be posted
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
// Pass TRUE or 1 if you want to wait for and catch the response against the request made
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// For Debug mode; shows up any error encountered during the operation
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Execute the request
$response = curl_exec($ch);

echo $response;

在控制器中:

function action(){

    //get properties of the file
    //$_FILES['Filedata']['name'];
    //$_FILES['Filedata']['size'];
    //$_FILES['Filedata']['tmp_name'];
    //savefile();



}

如果有人知道如何在不保存的情况下发布文件,那就太棒了。