Subir desde Node.js
Envía un archivo desde una app de Node.js a OpenFiles y guarda su enlace.
Node.js trae fetch, FormData y Blob incorporados, así que no necesitas ningún paquete más.
Necesitas un almacén (aquí photos) y un token con Upload files y photos. Consulta Tokens de API.
1. Guarda esto como upload.js y sustituye la dirección y el 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. Ejecútalo:
node upload.jsLa respuesta describe el archivo:
{
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. Guarda id y url junto con tu propio registro, por ejemplo el producto al que pertenece la foto, y usa url allí donde muestres el archivo.
Consulta Subir archivos para ver todas las opciones.