跨域名上传图片

  在我写一些小功能或者在上一篇文章提到的网站根据接口开发,这样就会遇到上传图片可能会跨域名。

  比如,我想在我的电脑上写一些程序,给同在局域网内的同事用,比如用“联图”生成二维码。在二维码上添加的logo必须是一张在线图片,也就是说需要一台服务器。但是我不想把程序放到服务器上去,图片的话,无所谓。这样的话,我就需要把同事上传的图片,先post到我的电脑上来,然后通过我电脑的wamp服务器再post到服务器上去,因为我和同事是局域网,上传时间基本为0,只有我上传到服务器需要点时间。所以整个过程在时间上并没有太大的问题。

  那么现在我就要在我电脑上的服务器上写一些方法,将同事上传的图片,我再上传到服务器上。我使用的是curl模拟post图片到服务器上去。

  这是一个我写的类,很简单,和大家分享一下,在服务器端你只需要写一个图片接受程序就可以了。

<?php
class postCurl{
    public $Url;            //请求链接
    public $Array;          //post的数据
    public function __construct() {
    }
    public function simulationPost($url, $array){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        //强制使用IPV4协议解析域名,否则在支持IPV6的环境下请求会异常慢
        @curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        if ($array){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $array);
        }

        $response = curl_exec($ch);
        curl_close($ch);
        //去除头部信息
        $response = strstr($response, '{');
        return $response;
    }
    public function simulationPostImg($url,$img){
        //生成临时图片文件
        $picTypeArray = explode('.', $img['name']);
        $count = count($picTypeArray);
        --$count;
        $picType = $picTypeArray[$count];                            //图片后缀名
        $newPicName = date('Ymdhis').'.'.$picType;                         //新的文件名
        $fileName = './upload/QRlogo/'.$newPicName;                   //临时图片文件名
        if(!is_uploaded_file($img['tmp_name'])){
            $this->ajaxReturn('','图片上传错误', '-1');
        }else{
            if(!move_uploaded_file($img['tmp_name'], $fileName)){
                $this->ajaxReturn('','图片上传错误1', '-2');
            }else{
          //这里的意思是,要确定图片的绝对地址,相对地址,图片是无法上传的
$data['mypic'] = '@'.YII_UP.'/upload/QRlogo/'.$newPicName; $uploadImg = $this->simulationPost($url, $data); unlink($fileName); //删除临时图片 return $uploadImg; } } } }

原理其实很简单,就是先在我电脑上的服务器先存这张图片,然后通过将这张图片的@绝对路径提交给服务器,就可以提交到服务器。

原文地址:https://www.cnblogs.com/xiashuo-he/p/3909530.html