0

我有一个带有图像的 url: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 发送到控制器以像普通用户上传一样进行处理?

谢谢

4

1 回答 1

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();



}

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

于 2012-07-20T13:31:45.420 回答