cancel
Showing results for 
Search instead for 
Did you mean: 

Upload a file in Alfresco Repository using php and curl

giancarlo
Champ in-the-making
Champ in-the-making
Hello,
I found in Alfresco web script lists

File upload
POST /alfresco/s/api/upload

and I'm tring to upload a file from local apache web server to remote alfresco 5.0.d repository.
I use a very simple PHP script:


$server_port = "8080"; // Alfresco port
$urlws = $server_ip ."/". $service_url ."api/upload?alf_ticket=". $ticket; // URL to Alfresco upload web script

$file = 'ico_html.jpg'; // File to upload

$postvars = array(
'filename' => $file,
'filedata' => '@'. realpath($file),
// destination =  node reference of the Alfresco folder I'd like to use. I used Alfresco Node brower to find it.
'destination' => 'workspace://SpacesStore/1ec885f5-bc0d-450a-9d65-a70a888e345d',
'uploaddirectory' =>'/',
'description' => 'File example',
'contenttype' => 'cm:content',
'overwrite' => 'true',
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);   
curl_setopt($ch, CURLOPT_PORT, $server_port);
curl_setopt($ch, CURLOPT_URL, $urlws);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
$connection = curl_exec($ch);


Conection is ok but alfresco response is:

    "code" : 400,
    "name" : "Bad Request",
    "description" : "Request sent by the client was syntactically incorrect."

I tried in a different way adding json instead of $postvars array:

$json = json_encode($postvars);

but with or without command

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));

the result is the same:


"code" : 500,
"name" : "Internal Error",
"description" : "An error inside the HTTP server which prevented it from fulfilling the request."
 
"message" : "11170048 Unexpected error occurred during upload of new content.",

Have somebody some working solution?
Thanks al lot
1 ACCEPTED ANSWER

adrie7tp1
Champ in-the-making
Champ in-the-making

Hi,

After some trial and error the following procedure works fine. Before you start:

1) be sure to have a valid user in Alfresco, preferably member of the group ALFRESCO_ADMINISTRATORS;

2) create an upload folder in the Alfesco repository and find the full nodeRef of it;

3) put a test-document in the PHP directory you are using for this test, named 'test-doc.txt'.

Find my full PHP code below (version 5.4 where CURLFile is not available, so use '@' before the name of the file to upload). Note the settings of 'content-type' as well as the POST-field types in the CURL definitions.

<?php

// file upload to Alfresco repo, PHP version 5.4

$debug = true;

set_error_handler("customError");

date_default_timezone_set('Europe/Berlin');

$ch = curl_init();

define ('USERNAME', '------');

define ('PASSWORD', '------');

define ('LOGINURL', 'http://--------:8080/alfresco/service/api/login');

define ('UPLOADURL', 'http://--------:8080/alfresco/service/api/upload');

define ('UPLOADDIR', 'workspace://SpacesStore/aa90950d-de65-4523-9adb-c2590a7d148d');

define ('TESTFILE', 'test-doc.txt');

define ('TESTTYPE', 'text/plain');

$logindata = array(

'username' => USERNAME,

'password' => PASSWORD

);

$data_str = json_encode($logindata);

// setup login (POST)

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, LOGINURL);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute the the login request

$result = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo 'Login: '. $data_str . ' ;<br>Result: '. $result . ';<br>The status is ' . $status;

$ticket = json_decode($result)->data->ticket;

echo ';<br>The ticket is: ' . $ticket;

// setup upload

$uploadUrl = UPLOADURL . '?alf_ticket=' . $ticket;

// $args = new CURLFile($filename, $type, $filename); // does not exist PHP 5.4

$fields = array(

'nodeType'=>'cm:content',

'filedata'=>'@' . TESTFILE,

'type'=>TESTTYPE,

'destination'=>UPLOADDIR,

'uploaddirectory'=>'/',

'overwrite'=>true

);

curl_setopt($ch, CURLOPT_URL, $uploadUrl);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));

curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

$result = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo '<br>End state: ' . $status . '<br>Alfresco response: ';

print_r($result);

curl_close($ch);

function customError($errno, $errstr, $errfl, $errln) {

//Merk op: geen melding in JSON response TODO?

global $debug;

if (is_bool($debug)) {

if ($debug) echo "<br><b>ERROR:</b> [$errno] $errstr in line $errln" ;

}

}

?>

View answer in original post

8 REPLIES 8

openpj
Elite Collaborator
Elite Collaborator

luharry
Champ on-the-rise
Champ on-the-rise

hello ,i wanted to know it too.Did you solve your problem now?

luharry
Champ on-the-rise
Champ on-the-rise

hi ,i use your method successful upload some file to alfresco service, the key is that you must get $ticket by url(http://localhost:8080/alfresco/service/api/login?u=admin&pw=123456 ).

Hi,
I got the ticket id too but the problem remains same
my script is 

      $urlws = 'http://' . $user . ':' . $pw . '@' . $server . ':' . $port . '/alfresco/service/api/upload?alf_ticket=' . $ticket;
        $fileName = '123.png';
        $filepath = 'C:\xampp\htdocs\SuitCrmAlfresco_IssuesFixation\upload\123.png';
        $postvars = array(
            'filename' => $fileName,
            'filedata' => '@' . getcwd() . "\\" . $filepath,
            'destination' => $createFolderResponse,
            'uploaddirectory' => '/',
            'description' => 'File example',
            'contenttype' => 'cm:content',
            'overwrite' => 'true',
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_PORT, $port);
        curl_setopt($ch, CURLOPT_URL, $urlws);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
        $uploadFileResponse = json_decode(curl_exec($ch));
        echo("<pre>");
        print_r($uploadFileResponse);exit;
 

And I got this Error

stdClass Object (     [status] => stdClass Object         (             [code] => 400             [name] => Bad Request             [description] => Request sent by the client was syntactically incorrect.         )      [message] => Required parameters are missing     [exception] =>      [callstack] => Array         (         )      [server] => Community v5.2.0 (re21f2be5-b22) schema 10,057     [time] => Oct 31, 2017 5:00:48 PM ) 

adrie7tp1
Champ in-the-making
Champ in-the-making

Hi, I'm struggling with the same issue. Did you resolve it in the meantime? Please let me know. Adrie.

hi adrie,
did you find any solution ?

I'm using alfresco 5.2 the url of the api is different but perhaps the way it works and parameters are the same, here is a working upload file in php :

<?php

//DATA
$ticket = 'TICKET_xxxxxxxxxxxxxxxxxxxxx';
$dest = '-root-';
$pdfnode = 'becb7769-8db9-4e6b-806b-a2ec1f5830d3';
$server = 'http://localhost';
$port = ':8080';
$filename = 'demo.docx';
$type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
$url = $server.$port.'/alfresco/api/-default-/public/alfresco/versions/1/nodes/'.$dest.'/children?alf_ticket='.$ticket;

$ch = curl_init($url);

$args = new CurlFile($filename,$type,$filename);

$data = array(
'nodeType'=>'cm:content',
'filedata'=>$args
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);

$result = curl_exec($ch);

for the test the file i upload is in the same directory than my script

adrie7tp1
Champ in-the-making
Champ in-the-making

Hi,

After some trial and error the following procedure works fine. Before you start:

1) be sure to have a valid user in Alfresco, preferably member of the group ALFRESCO_ADMINISTRATORS;

2) create an upload folder in the Alfesco repository and find the full nodeRef of it;

3) put a test-document in the PHP directory you are using for this test, named 'test-doc.txt'.

Find my full PHP code below (version 5.4 where CURLFile is not available, so use '@' before the name of the file to upload). Note the settings of 'content-type' as well as the POST-field types in the CURL definitions.

<?php

// file upload to Alfresco repo, PHP version 5.4

$debug = true;

set_error_handler("customError");

date_default_timezone_set('Europe/Berlin');

$ch = curl_init();

define ('USERNAME', '------');

define ('PASSWORD', '------');

define ('LOGINURL', 'http://--------:8080/alfresco/service/api/login');

define ('UPLOADURL', 'http://--------:8080/alfresco/service/api/upload');

define ('UPLOADDIR', 'workspace://SpacesStore/aa90950d-de65-4523-9adb-c2590a7d148d');

define ('TESTFILE', 'test-doc.txt');

define ('TESTTYPE', 'text/plain');

$logindata = array(

'username' => USERNAME,

'password' => PASSWORD

);

$data_str = json_encode($logindata);

// setup login (POST)

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, LOGINURL);

curl_setopt($ch, CURLOPT_POST, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_str);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute the the login request

$result = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo 'Login: '. $data_str . ' ;<br>Result: '. $result . ';<br>The status is ' . $status;

$ticket = json_decode($result)->data->ticket;

echo ';<br>The ticket is: ' . $ticket;

// setup upload

$uploadUrl = UPLOADURL . '?alf_ticket=' . $ticket;

// $args = new CURLFile($filename, $type, $filename); // does not exist PHP 5.4

$fields = array(

'nodeType'=>'cm:content',

'filedata'=>'@' . TESTFILE,

'type'=>TESTTYPE,

'destination'=>UPLOADDIR,

'uploaddirectory'=>'/',

'overwrite'=>true

);

curl_setopt($ch, CURLOPT_URL, $uploadUrl);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));

curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

$result = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo '<br>End state: ' . $status . '<br>Alfresco response: ';

print_r($result);

curl_close($ch);

function customError($errno, $errstr, $errfl, $errln) {

//Merk op: geen melding in JSON response TODO?

global $debug;

if (is_bool($debug)) {

if ($debug) echo "<br><b>ERROR:</b> [$errno] $errstr in line $errln" ;

}

}

?>