图像未使用 PHP cURL 通过 REST API 上传到服务器



我正在尝试通过REST API将图像上传到服务器。所以我使用了PHP cURL。但是我遇到文件没有上传到服务器端。我哪里做错了?请帮忙。下面是我的代码

<?php
$resp = "";
//check is POST
if (isset($_POST['submit'])) {
//check image upload, your want to check for other things too like: is it an image?
if(isset($_FILES['file']['name'])){
//make filename for new file
$uploadfile = basename($_FILES['file']['name']);
//move the upload
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('file'=> dirname(__FILE__).'/'.$uploadfile),
CURLOPT_HTTPHEADER => array(
"Content-Type: multipart/form-data; boundary=--------------------------516718006976498379520930"
),
));
$resp = curl_exec($curl);
curl_close($curl);
}
}
else {
$resp = "Upload a valid image file";
}
}
?>
<form runat="server" id="form" enctype="multipart/form-data" method="POST" action="">
<div class="upload">
<div id="upload-image">Upload Image</div>
<input type="file" name="file" id="file">
</div>submit" name="submit" id="main" value="Match Face"></input>
</form>

根据您的代码,只需使用以下代码。我希望它能奏效。

$ch = curl_init('http://example.com/');
curl_setopt($ch, CURLOTP_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => new CURLFile(dirname(__FILE__).'/'.$uploadfile)));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);

让我知道它是否有效。

您将文件上传到本地并在服务器中发送本地地址 在服务器文件中,您必须不在本地编码

<?php
if(isset($_FILES['file']['name'])){
$picurl = $this->UploadPic($_FILES['file']['name']);
}
publick function UploadPic($file){
//your uploader code here
//at the end you must return address
}
?>

最新更新