Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload Files in php using REST

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";
?>
like image 589
Charm_quark Avatar asked Apr 02 '13 23:04

Charm_quark


People also ask

Can we upload file using REST API?

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.

How do I send a file to REST API?

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.


2 Answers

I think you should be looking for $_FILES['file_contents'] and not $_POST['file']. – user1190992

like image 142
Charm_quark Avatar answered Oct 16 '22 10:10

Charm_quark


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);
like image 28
umesh bhanderi Avatar answered Oct 16 '22 11:10

umesh bhanderi