我在laravel做项目。表单提交后,我想将上传的文件移动到其余的api文件夹。 为此,我在我的控制器方法中调用了curl函数。
Controller.php这样
{
if($request->hasFile('filefield')){
$file = $request->file('filefield');
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file);
finfo_close($finfo);
$filename = $file->getClientOriginalName();
$method = 'POST';
$url = 'engagev1be.taarago.in/superadmin';
$data = array('file' => new \CurlFile($file,$mimeType,$filename), 'oldpath' =>$oldpath,'id'=>$id);
$result = $this->CallAPI($method,$url,$data);
}
}
和 CallAPI功能就像,
public function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
静止api我的 Route.php 是,
Route::post('superadmin', 'SuperadminController@uploadimg');
和 SuperadminController @ uploadimg 是,
public function uploadimg(Request $request){
$file = $request->file;
$oldpath = $request->oldpath;
$id = $request->id;
$editProvider = Provider::findOrFail($id);
if($file){
$filename = $file->getClientOriginalName();
$filename = str_replace('%', ' ', $filename);
$newpath = 'images/provider_images/'.$id;
if (!file_exists($newpath)) {
File::makeDirectory($newpath, 0777, true, true);
$newpath = 'images/provider_images/'.$id;
}
$success = move_uploaded_file($oldpath,$newpath.'/'.$filename);
$editProvider->profile_pic = $newpath.'/'.$filename;
$editProvider->update();
return $success ;
}
}
在这种情况下,$ success返回none,因为文件没有上传。 我正在做什么,当我这样做时,
dd($request->all());
然后它的结果就是,
array:3 [▼
"oldpath" => "/tmp/phpmyoWT4"
"id" => "61"
"file" => UploadedFile {#30 ▼
-test: false
-originalName: "images.png"
-mimeType: "image/png"
-size: 5126
-error: 0
}
]
这意味着,文件成功返回到其余的api但没有上传。