透過 php curl 上載image給對方?

請問一下如何透過 curl 上載image給對方?

curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: multipart/form-data; boundary=boundary;', 
      'Content-Length: ' . strlen($data_string))
  );

因為對方不是 php 接收而是nodejs
如何實現跨server的文件上載?
有大神嗎

阅读 4.2k
4 个回答

以前我也给过我的建议,我还是依旧觉得你应该学多点基础课程,但作为答题者对于新人就多见少怪。
根据你的问题描述,使用的方式是curl来上传数据给对方,我的思路方法是
1、上面也有人提及相关的思路了,将图片转化为base64,然后你会获得一串base64的编码字符
2、用curl的post方法传输这些base64的编码字符,相当于你的服务器端以curl模拟表单post提交的方式给对方
3、接收方是nodejs,那么你需要对方写好一个接受post数据的API接口,对方API里面需要包含base64解码的功能,将你发送过去的编码再次转换为图片保存

第一步、这里假设1.jpg是你需要上传的图片,开始转换图片

function base64_encode_image ($file_location=string,$filetype=string) {
    if ($file_location) {
        $imgbinary = fread(fopen($file_location, "r"), filesize($file_location));
        return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
    }
}
//$file_location就是图片的位置,$filetype就是图片的类型,比如jpg、png、bmp
$encoded = base64_encode_image ($fread);

第二步,通过curl的post方法传输这些base64的编码字符,

//$encoded为上面获得的base64编码
/**
 * 模拟post进行url请求
 * @param string $url
 * @param string $param
 */
function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    
    $postUrl = $url;
    $curlPost = $param;
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return $data;
}

//$encoded为第一步得到的base64编码,$url就是对方的nodejs的API(URL)地址
request_post($url, $encoded);

第三步,是关于nodejs,不是这个问题的关注点,我也不懂过多nodejs,不多做回答

上述的用例,引用的来源于
http://php.net/manual/zh/func...
https://www.cnblogs.com/ps-bl...

multipart/form-data是标准的上传协议,跟什么语言的服务器无关的。
curl命令行是用--form这个参数来指定上传文件的,你查一下php的curl选项,应该有对应的东西。不需要自己手动设定Content-Type和Content-Length头的。

簡單點轉base64吧

$ch = curl_init();  
$data = array('name' => 'Foo', 'file' => new CURLFille('/home/vagrant/test.png'));  
curl_setopt($ch, CURLOPT_URL, 'http://localhost/test/curl/load_file.php');  
curl_setopt($ch, CURLOPT_POST, 1);  
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);  
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
curl_exec($ch);  
$aStatus = curl_getinfo($ch);  
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题