0

I have a list of attachments' urls and would like to download it in one click. I have loaded the urls as an array in javascript. Then I use XMLHttpRequest to get the file content. However, it seems like the header or authentication is not correct when sending to Circuitsandbox (and later to Circuit for productive), I always get error 401 or 404 even though that url can be downloaded on browser.

So my question is what header/authentication should I use for my request?

This is my example:

var auth = user + ':' + password; var hash = Base64.encode(auth); ... xhr.setRequestHeader("Authorization", "Basic " + hash );

Should I use my user (email) and password for Circuitsandbox here?

Thanks you very much for any hint.

1 Answers1

0

The Circuit file api to download attachments does not support Basic Authentication. Since you are running this in the browser which already has a session, all you need is to set xhr.withCredentials to true. This will use the cookie of your current session. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

I just created an example jsbin that downloads the attachments of a post. Just enter the itemId of the post. You can see the itemId when right-clicking the timestamp in a post on the Circuit webclient.

https://output.jsbin.com/napenuy

client.getItemById(itemId.value) 
.then(item => {
  console.log('Attachments:', item.attachments);

  item.attachments.forEach(file => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', file.url, true);
    xhr.withCredentials = true; 
    xhr.onload = function(e) {
      if (this.status == 200) {
        result.innerHTML += `<br>${file.fileName}:<br>${this.responseText}`;  
      } 
    }
    xhr.send();    
  })
}) 
.catch(console.error);
Roger Urscheler
  • 774
  • 2
  • 6
  • 11