Search code examples
javascriptnode.jsuploadstrapi

Post an image to Strapi programmatically with NodeJS


This Upload documentation is all I can find which gives a browser based example using the FormData api.

All it states is that you POST to /uploads with a files parameter of type Buffer/Stream. Here's where I am at so far:

fs.readFile(filepath, (err, data) => {
    needle('post','http://localhost:1337/upload', {files: data}, {
        multipart: true,
    }).then(response => {
        console.log(response.body);
        if(response.body.data)
            console.log(response.body.data.errors)
    });
});

The post is successful but something isn't quite right, the image is registered but missing in the media library with the name of 'files' instead of anything meaningful.

enter image description here

Example response from the post:

[
  {
    id: 170,
    name: 'files',
    alternativeText: null,
    caption: null,
    width: 768,
    height: 1024,
    formats: {
      thumbnail: [Object],
      large: [Object],
      medium: [Object],
      small: [Object]
    },
    hash: 'files_d98a49e7f5',
    ext: '',
    mime: 'application/octet-stream',
    size: 159.62,
    url: '/uploads/files_d98a49e7f5',
    previewUrl: null,
    provider: 'local',
    provider_metadata: null,
    created_at: '2021-06-09T17:12:52.951Z',
    updated_at: '2021-06-09T17:12:52.951Z',
    related: []
  }
]

I have also tried using the node module form-data to mimic the example provided in the documentation.

let form = new FormData();
form.append('files', fs.createReadStream("./test.jpg"))
let data = form //attempt1
let data = {files: form} //attempt2
let data = {files: form.toString()} //attempt3
needle('post','http://localhost:1337/upload', data, {
    multipart: true,
})

But this generally returned 400 bad request with the following response:

{ id: 'Upload.status.empty', message: 'Files are empty' } 

Solution

  • Replace the needle http request with the submit method provided by the form-data module like so:

    let form = new FormData();
    
    form.append('files', fs.createReadStream("./testimage.jpg"))
    form.append('fileInfo', JSON.stringify({
        alternativeText: 'example'
    }));
    
    form.submit('http://localhost:1337/upload', (err,res) => {
        res.on('data', function (chunk) {
            console.log(JSON.parse(chunk)) //response file object
          });
    })