【发布时间】:2020-01-20 14:33:24
【问题描述】:
我正在尝试通过 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>
【问题讨论】:
-
停止尝试添加您自己的 Content-Type 标头。 cURL 不知道您在其中指定的边界值,它自己创建。基本上,您这样做是对接收者谎称您的数据实际上是如何构造的。
-
另外,您并没有首先发送实际的文件内容。
CURLOPT_POSTFIELDS => array('file'=> dirname(__FILE__).'/'.$uploadfile)- 仅是文件的本地路径,在参数名称file下发送。去阅读php.net/manual/en/curlfile.construct.php 了解它是如何工作的。 -
感谢您的评论,我正在学习 cURL PHP 以及我从 Postman 获得的这些代码。我什至添加了代码
new CURLFILE,但它也不起作用。