Is there a way to upload a file from a client side to the server using REST using PHP,
I am trying to use the below code, and it is not working from me.
<?php
$file_to_upload = array('file_contents'=>'@c:\\test.txt');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/api/upload.php');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSER, TRUE);
curl_setopt($ch, CURLOPT_UPLOAD, TRUE);
curl_setopt($ch, CURLOPT_POST,TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $file_to_upload);
curl_exec($ch) or die( curl_error($ch) );
$error = curl_error($ch);
curl_close ($ch);
echo " Server response: ".$result;
echo " Curl Error: ".$error;
?>
and my upload.php
$uploaddir = realpath('./') . '/';
$uploadfile = $uploaddir . basename($_POST['file']['name']);
echo $uploadfile;
echo "\n";
echo '<pre>';
echo $_POST['file']['tmp_name'];
if (move_uploaded_file($_POST['file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
echo "\n<hr />\n";
print_r($_POST);
print "</pr" . "e>\n";
?>
REST API File Upload with Java In the above code block, we have created an endpoint of type HTTP Post that is waiting for file. This endpoint prints the name of the external file to the console of the application. That's all we'll do for File Upload on the code side.
To attach a file, you must include it with the Body as form-data. Once you are in the Body → form-data fields, you must enter a KEY . This should be “file” or whichever value you specified in the @RequestPart(“[value]”) . After doing so, a dropdown will appear that gives you the option of Text or File.
I think you should be looking for
$_FILES['file_contents']
and not$_POST['file']
. – user1190992
php5.5+
$filePath = $_FILES['file_upl']['tmp_name'];
$type=$_FILES['file_upl']['type'];
$fileName = $_FILES['file_upl']['name'];
$data = array('file_upl' => curl_file_create($filePath, $type, $fileName));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost/api/upload.php');
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With