【问题标题】:php image upload using curl request使用 curl 请求的 php 图片上传
【发布时间】:2016-11-08 12:53:43
【问题描述】:

我正在尝试通过 imageUploader.php 将图像文件上传到服务器。我需要从我的角度脚本和 php 脚本上传图像。我的 Angular http 请求成功上传了图片,但 php 脚本未能上传图片文件。

这是角度请求:

fd = new FormData();
fd.append('file', file);

    $http
    .post(uUrl, fd, {
        transformRequest: angular.identity,
        headers: {
            'Content-Type': "multipart/form-data"
        }
    })

这是php请求

    $data['file'] = new CurlFile( $data_string['tmp_name'], $data_string['type']); 

    if (! isset ( $this->conType ))
        $this->conType = 'multipart/form-data';
    $ch = curl_init ( $this->baseUrl  ); 
    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); 
    $this->addHeader ( 'Content-Type', $this->conType ); 
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $this->headerArray );
    $result = curl_exec ( $ch );

    public function addHeader($k, $v) {
        array_push ( $this->headerArray, $k . ": " . $v );
    }

问题是,如果我在php脚本中去掉multipart/form-data部分,图片上传成功,但是在服务器查看时,图片内容不能被查看。好像上传图片时图片损坏了。

【问题讨论】:

    标签: php angularjs


    【解决方案1】:

    试试这个代码,它将帮助你使用 curl 上传文件

    $ch = curl_init();
    //$data = array('name' => 'Foo', 'file' => '@/path/to/image.jpeg');
    $data['file'] = new CurlFile( $data_string['tmp_name'], $data_string['type']); 
    curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
    curl_setopt($ch, CURLOPT_POST, 1);
    //CURLOPT_SAFE_UPLOAD defaulted to true in 5.6.0
    //So next line is required as of php >= 5.6.0
    curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_exec($ch);
    

    【讨论】:

    • 它给了我这个错误 不推荐使用@filename API 进行文件上传。请改用 CURLFile 类
    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 2011-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多