Search code examples
phpapicurltrello

cURL + PHP - Attachments in Trello cards


How are you?

Anybody who used the API for PHP Trello to send an attachment to a card can explain me better how it works?

I have an HTML page with some input type="text", select and input type="file" multiple

To send the data do trello API, I'm doing this way:

JAVASCRIPT

var files = document.getElementById('Trello attachment'). files;

var formData = new FormData();

for (i = 0; i <myFiles.length; i ++) {
  formData.append('file[]', myFiles[i]);
}
var ajax = new XMLHttpRequest();
ajax.open('POST', 'assets/php/ajaxResponse.php');
ajax.send(formData);

PHP ajaxResponse

if (! empty ($_ FILES)) {
  for ($i = 0; $i <count ($_FILES['file']['name']); $i++) {
    $chAttachment = curl_init();
    curl_setopt($chAttachment, CURLOPT_URL, 'https://api.trello.com/1/cards/tQxhxRJO/attachments?key=key&token=token');

    curl_setopt($chAttachment, CURLOPT_POSTFIELDS, http_build_query(
      variety(
        'name' => $_FILES ['file'] ['name'] [$i],
        'file' => $_FILES ['file'] ['tmp_name'] [$i]
      )
    ));

    curl_setopt($chAttachment, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec ($chAttachment);
    curl_close($chAttachment);
    print_r($result);
  }
}

The problem i'm facing is, with the API i can create the attachments on the tQxhxRJO ID card, however, in trello they show the filename because by curl_setopt i set up the name i want through the name param, but all uploaded files have 14 bytes, this means it doesn't it uploads correctly, when I click to download or open the attachments on the trello card, i can download the file, but, all my files named Upload, if you open the file with VSCode i.e, the contentcontains the filename who i sent.

Does anyone know how to upload via cURL correctly?

Thank you so much!


Solution

  • Solved!

    If anybody here need any help on how to upload the files using cURL in trello, here is the trick!

    for($i = 0; $i < count($_FILES['file']['name']); $i++){
     $args = array(
       'file' => new CurlFile($_FILES['file']['tmp_name'][$i], $_FILES['file']['type'][$i],$_FILES['file']['name'][$i]),
       'key'   => 'mykey',
       'token' => 'mytoken',
       'mimeType' => $_FILES['file']['type'][$i],
       'name' => $_FILES['file']['name'][$i]
     );
            
     $chAttachments = curl_init();
     curl_setopt($chAttachments, CURLOPT_URL,'https://api.trello.com/1/cards/' . $jsonDecoded['shortLink'] . '/attachments/');
     curl_setopt($chAttachments, CURLOPT_POST,1);
     curl_setopt($chAttachments, CURLOPT_POSTFIELDS, $args);
     $resultAttachments = curl_exec($chAttachments);
     curl_close($chAttachments);
    }