这里是用原生代码的上传的方法:
假设为:Qcloud
3.代码部份
public static function uploadToTencentyun_new($file_url_local,$file_url_server,$isDeleteLocalFile=true){
//error_reporting(E_ALL);
// 取原有的加载方法----根据情况可以删除
$oldFunctions = spl_autoload_functions();
// 逐个卸载----根据情况可以删除
if ($oldFunctions){
foreach ($oldFunctions as $f) {
spl_autoload_unregister($f);
}
}
//引用jdk
require '/wwwroot/mysite/Qcloud/vender/autoload.php';
$secretId = "云 API 密钥 SecretId"; //"云 API 密钥 SecretId";
$secretKey = "云 API 密钥 SecretKey"; //"云 API 密钥 SecretKey";
$region = "ap-shanghai"; //设置一个默认的存储桶地域
$cosClient = new Qcloud\Cos\Client(
array(
'region' => $region,
'credentials'=> array(
'secretId' => $secretId,
'secretKey' => $secretKey,
)
)
);
$upload_success = false;
$img_url = '';
$upload_msg = '';
### 上传文件流
try {
$bucket = "BucketName-APPID"; //存储桶名称 格式:BucketName-APPID
$key = $file_url_server;
$file = fopen($file_url_local, "rb");//本地文件绝对路径
if ($file) {
$result = $cosClient->putObject(array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $file));
//print_r($result);
$data = $result->toArray() ;
//print_r($data);
if(isset($data['Location']) && isset($data['Key'])){
$img_url = $data['Key'];
$upload_success = true;
}
}
} catch (\Exception $e) {
$upload_msg = $e->getMessage();
}
// 再将原来的自动加载函数放回去----根据情况可以删除
if ($oldFunctions){
foreach ($oldFunctions as $f) {
spl_autoload_register($f);
}
}
//删除本地文件
if($isDeleteLocalFile) {
@unlink($file_url_local);
}
//返回信息
if($upload_success){
return array('id' => '0001','msg' => '上传成功','info'=>$img_url,'more'=>'');
}
else{
return array('id' => '0002','msg' => '上传失败','info'=>$upload_msg);//返回‘上传失败’,并返回错误信息
}
}
4.调用
$local_file = '/wwwroot/mysite/a.jpg';//本地文件
$server_key_name = '/upload/20191118/a.jpg';//远程文件名
$new_upload_class -> uploadToTencentyun_new($local_file , $server_key_name , true);