Spanish Total.js
Italiano
Documentazione Per agenti IA
Indice

Caricare da Node.js

Invia un file da un'app Node.js a OpenFiles e conserva il suo link.

.md GitHub

Node.js ha fetch, FormData e Blob già integrati, quindi non ti serve nessun pacchetto in più.

Ti servono uno storage (qui photos) e un token con Upload files e photos. Leggi Token API.

1. Salva questo come upload.js e sostituisci l'indirizzo e il 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. Eseguilo:

node upload.js

La risposta descrive il 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. Salva id e url insieme al tuo record, per esempio il prodotto a cui appartiene la foto, e usa url ovunque mostri il file.

Leggi Caricare file per tutte le opzioni.

Fatto in Europa