使用curl进行文件上传无效

时间:2017-08-18 05:40:06

标签: php symfony curl

我试图在symfony中使用curl上传文件,但上传无效,代码如下。

public function filePassingAction(Request $request, $guid) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://192.168.0.41/lis/web/app_dev.php/interface/file-upload");
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, array(
            'file' => '@'.$this->getParameter('directory1').'/file.pdf',
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        ($result);
        return new JsonResponse($result);
    }

接受行动

public function fileUploadAction(Request $request) {
        $file = $request->files->get('file');
        // Generate a unique name for the file before saving it
        $fileName = md5(uniqid()) . '.' . $file->guessExtension();

        // Move the file to the directory where brochures are stored
        $file->move(
                $this->getParameter('directory2'), $fileName
        );

        return new JsonResponse();
    }

in service.yml

directory1: '%kernel.root_dir%/../web/uploads/directory1'
directory2: '%kernel.root_dir%/../web/uploads/directory2'

1 个答案:

答案 0 :(得分:2)

使用

  

真实路径

$file_name_with_full_path = $this->getParameter('directory1').'/file.pdf';

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
   'file' => '@'.realpath($file_name_with_full_path),
));

对于php 5.5 +

$file_name_with_full_path = $this->getParameter('directory1').'/file.pdf';

curl_setopt($ch, CURLOPT_POSTFIELDS, array(
   'file' => curl_file_create($file_name_with_full_path),
));