Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

How to add an attachment to a card with an image that is not saved locally? nodeJS

Jamahl M-D May 23, 2020

I'm saving an image file locally so I can ready it using `fs.createReadStream()` and append it to my `FormData` to send it to the REST api. Like this:

```
const fetch = require('node-fetch');
const Jimp = require('jimp');
const FormData = require('form-data');

// Save file locally
await Jimp.read(imagePNGURL).writeAsync(savedImagePath);

// Append it to the formdata using fs.createReadStream
const formData = new FormData();
formData.append('file', fs.createReadStream(savedImagePath));

// Send formData to api and image gets saved correctly
await fetch('TrelloUrl', { method: 'POST', body: formData })
```

Now I want to do the same thing but **without** saving the file locally but by using the image **buffer**. I've tried the following but I can't seem to make it work:

```
const fetch = require('node-fetch');
const Jimp = require('jimp');
const FormData = require('form-data');
const stream = require('stream');

// Save file to Buffer
const buffer = await Jimp.read(imagePNGURL).getBufferAsync('image/png');

// Convert buffer to stream
const bufferStream = new stream.PassThrough();
bufferStream.end(buffer);

// Try to append it to the formdata and send it to the api
const formData = new FormData();
formData.append('file', bufferStream); // Results in 400 Bad Request
formData.append('file', bufferStream.read()); // Results in empty image being uploaded

await fetch('TrelloUrl', { method: 'POST', body: formData })

---------
// Also tried to convert the buffer to stream like this:
const { Readable } = require('stream');

const bufferToStream = (buffer) => {
const stream = new Readable();
stream.push(buffer);
stream.push(null);

return stream;
};
formData.append('file', bufferToStream(buffer)); // Results in 400 Bad Request
formData.append('file', bufferToStream(buffer).read(); // Results in empty image being uploaded

```
How can I convert the `buffer` correctly to a `fs.ReadStream()` object so I can send it successfully to the api?

Or are there better ways to approach this?

All help is appreciated.

1 answer

1 accepted

1 vote
Answer accepted
Iain Dooley
Community Champion
May 25, 2020

@Jamahl M-D I have never been able to make file uploads like this work, but this guy reported he was able to the other day, I haven't tried it though ymmv:

https://community.atlassian.com/t5/Trello-questions/Re-Mime-types-of-attachments-uploaded-to-Trello/qaq-p/1382846/comment-id/26380#M26380

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events