Upload from Node.js
Send a file from a Node.js app to OpenFiles and keep its link.
Node.js has fetch, FormData and Blob built in, so you need no extra package.
You need a storage (here photos) and a token with Upload files and photos. See API tokens.
1. Save this as upload.js and replace the address and the token:
const Fs = require('fs');
const OPENFILES = 'https://files.example.com';
const TOKEN = 'YOUR_TOKEN';
async function upload(path, name, type) {
const form = new FormData();
form.append('file', new Blob([Fs.readFileSync(path)], { type }), name);
const res = await fetch(OPENFILES + '/upload/photos/?hostname=1', {
method: 'POST',
headers: { 'x-token': TOKEN },
body: form
});
if (!res.ok)
throw new Error('Upload failed: ' + res.status + ' ' + await res.text());
return res.json();
}
upload('sunset.png', 'sunset.png', 'image/png').then(console.log);2. Run it:
node upload.jsThe answer describes the file:
{
id: 'JapO8K1j960f',
name: 'sunset.png',
size: 2795,
type: 'image/png',
width: 640,
height: 480,
ext: 'png',
url: 'https://files.example.com/files/photos/JapO8K1j960f-p9.png'
}3. Save id and url with your own record, for example the product the photo belongs to, and use url wherever you show the file.
See Upload files for all options.