项目场景:
绝对路径图片转换成文件流请求文件上传接口
因为我的uploadImgAndFile 接口接收的是前端传的文件流来调用华为云obs 如果我想将一张绝对路径的文件传到华为云 需要将其转换成文件流来请求接口 以下是代码。
@Override
function upload($url='https://api.xhjrbkp.com/api/file/uploadImgAndFile', $data='', $file='https://img.xhjrbkp.com/MTYzOTEwNjc5NXE1T3NDeDdQ.6m.png') {
$param = [
'file' => file_get_contents($file),
'type' =>1,
];
if (!empty($data)) {
arrary_merge($data, $param);
}
$delimiter = uniqid();
$data = '';
$eol = "\r\n";
$upload = $param['file'];
unset($param['file']);
foreach ($param as $name => $content) {
$data .= "--" . $delimiter . "\r\n"
. 'Content-Disposition: form-data; name="' . $name . "\"\r\n\r\n"
. $content . "\r\n";
}
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="file"; filename="https://img.xhjrbkp.com/MTYzOTEwNjc5NXE1T3NDeDdQ.6m.png"' . "\r\n"
. 'Content-Type: image/gif' . "\r\n\r\n";
$data .= $upload . "\r\n";
$data .= "--" . $delimiter . "--\r\n";
$post_data = $data;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"Content-Type: multipart/form-data; boundary=" . $delimiter,
"Content-Length: " . strlen($post_data),
]);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}
@Override
public function uploadImgAndFile(Request $request){
$file=$request->file('file');
$type=input('type');
$id=input('id');
if($type==1){
$prefix='platform_'.$id;
}elseif($type==2){
$prefix='general_backstage';
}
if(empty($file)){
$data = ['code' => 400, 'msg' => '文件不能为空', 'data' => ''];
return json($data);
}else{
$info = $file->getInfo();
$maxSize = 10;
$allowed_extensions = ["png", "jpg", "gif","pdf"];
$data = ['code' => 400, 'msg' => '上传文件失败', 'data' => ''];
if ($info['error']>0) {
$data['msg'] = $_FILES["file"]["error"];
return json($data);
} else {
if (!in_array(strtolower(substr(strrchr($info['name'], '.'), 1)), $allowed_extensions)) {
$data['msg'] = "请上传" . implode(",", $allowed_extensions) . "格式的文件";
return json($data);
}
if ($info['size'] > $maxSize * 1024 * 1024) {
$data['msg'] = "文件大小限制" . $maxSize . "M";
return json($data);
}
}
$newFile = $prefix.'/'.date('Ymd')."/".getRandomString(10).strrchr($info['name'], '.');
try {
$resp = $this->obsClient->putObject([
'Bucket' => $this->bucketName,
'Key' => $newFile,
'Body' =>$file,
'ACL' => ObsClient::AclPublicRead,
]);
if($resp ['HttpStatusCode']==200){
$data = [
'code' => 200,
'msg' => '上传文件成功',
'data' => $resp ['ObjectURL'],
];
}else{
$data['mess'] = $resp ['HttpStatusCode'].':'.$resp['Reason'];
}
} catch ( ObsException $e ) {
$data['msg']=$e->getMessage();
}
return json($data);
}
}
批注:
用于个人总结,菜鸟一枚大佬轻喷,如有问题欢迎指证,如果对大家有帮助那再好不过;
|