鍍金池/ 問答/PHP  Linux/ 透過 php curl 上載image給對(duì)方?

透過 php curl 上載image給對(duì)方?

請(qǐng)問一下如何透過 curl 上載image給對(duì)方?

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

因?yàn)閷?duì)方不是 php 接收而是nodejs
如何實(shí)現(xiàn)跨server的文件上載?
有大神嗎

回答
編輯回答
艷骨

multipart/form-data是標(biāo)準(zhǔn)的上傳協(xié)議,跟什么語言的服務(wù)器無關(guān)的。
curl命令行是用--form這個(gè)參數(shù)來指定上傳文件的,你查一下php的curl選項(xiàng),應(yīng)該有對(duì)應(yīng)的東西。不需要自己手動(dòng)設(shè)定Content-Type和Content-Length頭的。

2017年8月30日 07:27
編輯回答
礙你眼

以前我也給過我的建議,我還是依舊覺得你應(yīng)該學(xué)多點(diǎn)基礎(chǔ)課程,但作為答題者對(duì)于新人就多見少怪。
根據(jù)你的問題描述,使用的方式是curl來上傳數(shù)據(jù)給對(duì)方,我的思路方法是
1、上面也有人提及相關(guān)的思路了,將圖片轉(zhuǎn)化為base64,然后你會(huì)獲得一串base64的編碼字符
2、用curl的post方法傳輸這些base64的編碼字符,相當(dāng)于你的服務(wù)器端以curl模擬表單post提交的方式給對(duì)方
3、接收方是nodejs,那么你需要對(duì)方寫好一個(gè)接受post數(shù)據(jù)的API接口,對(duì)方API里面需要包含base64解碼的功能,將你發(fā)送過去的編碼再次轉(zhuǎn)換為圖片保存

第一步、這里假設(shè)1.jpg是你需要上傳的圖片,開始轉(zhuǎn)換圖片

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進(jìn)行url請(qǐng)求
 * @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);//抓取指定網(wǎng)頁
    curl_setopt($ch, CURLOPT_HEADER, 0);//設(shè)置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結(jié)果為字符串且輸出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
    $data = curl_exec($ch);//運(yùn)行curl
    curl_close($ch);
    return $data;
}

//$encoded為第一步得到的base64編碼,$url就是對(duì)方的nodejs的API(URL)地址
request_post($url, $encoded);

第三步,是關(guān)于nodejs,不是這個(gè)問題的關(guān)注點(diǎn),我也不懂過多nodejs,不多做回答

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

2018年5月10日 19:20
編輯回答
不二心

簡(jiǎn)單點(diǎn)轉(zhuǎn)base64吧

2018年2月2日 05:03
編輯回答
薄荷糖
$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);  
2018年2月12日 22:47