Search code examples
javascripttrello

How to attach image(s) to a new Trello card from the JS client library?


While adding a new card with the trello_client.js library, I want to attach an image or more. The documentation only mentions that fileSource is "A file".

Data URI didn't work as is, and blobs are usually appended to FormData objects so I'm not sure how to approach this and didn't find working examples.

And is it even possible to attach multiple files along with the card creation, or only later, by separate posts here?


Solution

  • The client.js library doesn't support attaching file attachments. You'll need to use a standard XHR and FormData object.

    Here's some sample code: https://plnkr.co/edit/PjJsfMgJuJaM5A83RAiW

    The relevant bits of HTML:

    <input type="file" id="chooser"/>
    <button onclick="upload();">Upload</button>
    

    and the javascript:

    // Setup
    var TOKEN = "";
    var KEY = "";
    var CARD = "";
    
    function upload() {
      var formData = new FormData();
    
      formData.append("token", TOKEN);
      formData.append("key", KEY);
    
      // HTML file input, chosen by user
      formData.append("file", document.getElementById('chooser').files[0]);
    
      var request = new XMLHttpRequest();
      request.open("POST", "https://api.trello.com/1/cards/" + CARD + "/attachments");
      request.send(formData);
    }