curl php参数,php curl上传文件和参数

1.根据文件路径上传

$url = "http://localhost/file/upload";

$post_data = array(

"filename" => "abc.png",

"bar" => "foo",

//要上传的本地文件地址

"file" = > "@/User/www/test/abc.png"

);

$ch = curl_init();

curl_setopt($ch , CURLOPT_URL , $url);

curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch , CURLOPT_POST, 1);

curl_setopt($ch , CURLOPT_POSTFIELDS, $post_data);

$output = curl_exec($ch);

curl_close($ch);

echo $output;

上传文件需要用@加上文件的绝对路径

2.根据文件内容上传

class CurlUploadFile

{

protected static $url;

protected static $delimiter;

protected static $instance;

public function __construct() {

//上传地址

static::$url = 'http://localhost/file/upload';

//分割符

static::$delimiter = uniqid();

}

public function putFile($param) {

$post_data = static::buildData($param);

$curl = curl_init(static::$url);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_POST, true);

curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

curl_setopt($curl, CURLOPT_HTTPHEADER, [

"Content-Type: multipart/form-data; boundary=" . static::$delimiter,

"Content-Length: " . strlen($post_data)

]);

$response = curl_exec($curl);

curl_close($curl);

$info = json_decode($response, true);

return $response;

}

private static function buildData($param){

$data = '';

$eol = "\r\n";

$upload = $param['file'];

unset($param['file']);

foreach ($param as $name => $content) {

$data .= "--" . static::$delimiter . "\r\n"

. 'Content-Disposition: form-data; name="' . $name . "\"\r\n\r\n"

. $content . "\r\n";

}

// 拼接文件流

$data .= "--" . static::$delimiter . $eol

. 'Content-Disposition: form-data; name="file"; filename="' . $param['filename'] . '"' . "\r\n"

. 'Content-Type:application/octet-stream'."\r\n\r\n";

$data .= $upload . "\r\n";

$data .= "--" . static::$delimiter . "--\r\n";

return $data;

}

public static function getInstance() {

if(!static::$instance){

static::$instance = new static();

}

return static::$instance;

}

}

调用上传

$data = array(

'type' => 'image',

'filename' => 'abc.png',

'filesize' => 58701, //分片上传

'offset' => 0,

'filetype' => 'image/png',

'originName' => 'abc.png',

'file'=>file_get_contents('abc.png')

);

$part = CurlUploadFile::getInstance()->putFile($data);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值