Download file via API

Share your custom code, plugins and themes.
Post Reply
thielem
Posts: 22
Joined: 12 Mar 2023, 22:30
Name: Moritz Thiele
Location: Germany, Berlin

Download file via API

Post by thielem »

Code: Select all

function py_api_with_file($process_id, $item_id, $FilenameArrayPlaceholder) {
    global $alerts;

    $url = VAR_API_SERVER . '/process_file/' . $process_id;
    $fileNames = explode(",", strval($FilenameArrayPlaceholder));
    $files = array();
    foreach ($fileNames as $value) {
        $files[] = attachments::parse_filename($value);
    }

    $postData = ['items_id' => $item_id];
    $fileData = []; 
		$counter = 0; 

		foreach ($files as $file) {
		    $cleanPath = stripslashes(strval($file['file_path']));
		    // Use the counter to dynamically create the key as files[n]
		    $key = 'files[' . $counter . ']';
		    $fileData[$key] = new CURLFile($cleanPath, 'application/octet-stream', $file['name']);
		    $counter++; 
		}
		

    // Initialize and set CURL options
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, array_merge($postData, $fileData));

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        $errorMessage = 'Request Error:' . curl_error($ch);
        if (is_object($alerts)) {
            $alerts->add($errorMessage, 'error');
        }
    } else {
        handle_api_response($response);
    }

    curl_close($ch);
}
I am using this custom PHP to download files (which is not possible through the API).
Process_id is parsed by my receiving server, FilenameArrayPlaceholder is the comma-separated list of filenames that rukovoditel outputs when I use the attachment field as a placeholder in the automated action.

@support if file download from attachments and onlyoffice fields could be added natively, that would be amazing!
Post Reply