Caricamento dell'immagine con codifica base64 su Amazon S3 tramite Node.js


99

Ieri ho fatto una sessione di programmazione notturna profonda e ho creato una piccola app node.js / JS (beh, in realtà CoffeeScript, ma CoffeeScript è solo JavaScript, quindi diciamo JS).

qual è l'obiettivo:

  1. il client invia un canvas datauri (png) al server (tramite socket.io)
  2. il server carica l'immagine su amazon s3

il passaggio 1 è terminato.

il server ora ha una stringa a la

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt...

la mia domanda è: quali sono i miei prossimi passi per "trasmettere" / caricare questi dati su Amazon S3 e creare un'immagine reale lì?

knox https://github.com/LearnBoost/knox sembra una fantastica libreria per Mettere qualcosa su S3, ma quello che mi manca è la colla tra la stringa di immagine codificata base64 e l'effettiva azione di caricamento ?

Eventuali idee, suggerimenti e feedback sono benvenuti.


4
Controllare questa risposta: stackoverflow.com/questions/5867534/...
akirk

Risposte:


209

Per le persone che stanno ancora lottando con questo problema. Ecco l'approccio che ho usato con aws-sdk nativo.

var AWS = require('aws-sdk');
AWS.config.loadFromPath('./s3_config.json');
var s3Bucket = new AWS.S3( { params: {Bucket: 'myBucket'} } );

all'interno del metodo del router: - ContentType dovrebbe essere impostato sul tipo di contenuto del file immagine

  buf = Buffer.from(req.body.imageBinary.replace(/^data:image\/\w+;base64,/, ""),'base64')
  var data = {
    Key: req.body.userId, 
    Body: buf,
    ContentEncoding: 'base64',
    ContentType: 'image/jpeg'
  };
  s3Bucket.putObject(data, function(err, data){
      if (err) { 
        console.log(err);
        console.log('Error uploading data: ', data); 
      } else {
        console.log('succesfully uploaded the image!');
      }
  });

Il file s3_config.json è: -

{
  "accessKeyId":"xxxxxxxxxxxxxxxx",
  "secretAccessKey":"xxxxxxxxxxxxxx",
  "region":"us-east-1"
}

2
[MissingRequiredParameter: chiave richiesta mancante "Key" nei parametri]
Nichole A. Miler

1
Chiave: req.body.userId Ho usato userId come chiave nei dati del post ... era molto tempo fa ... ma puoi dichiarare qualsiasi stringa come chiave. Per assicurarsi che i file già presenti non vengano sovrascritti, mantenere la chiave univoca.
Divyanshu Das

@Divyanshu Grazie per questo esempio utile. Ho due dubbi: How to make S3 generates a unique KEY to prevent from overriding files?e If I don't set the ContentType, when I download the files I won't be able to get the correct file?voglio dire, otterrò un file così danneggiato? Grazie in anticipo!
alexventuraio

2
Il percorso della posizione @Marklar è fondamentalmente la chiave, ad esempio se il nome del tuo bucket è - bucketone e il nome della chiave è xyz.png, il percorso del file sarà bucketone.s3.amazonaws.com/xyz.png
Divyanshu Das

2
@Divyanshu Grazie per questa ottima risposta! Mi ha aiutato molto. Tuttavia, penso che ContentEncoding: 'base64'non sia corretto perché new Buffer(..., 'base64')decodifica la stringa con codifica base64 nella sua rappresentazione binaria.
Shuhei Kagawa

17

ok, questa è la risposta su come salvare i dati della tela su file

fondamentalmente è così nel mio codice

buf = new Buffer(data.dataurl.replace(/^data:image\/\w+;base64,/, ""),'base64')


req = knoxClient.put('/images/'+filename, {
             'Content-Length': buf.length,
             'Content-Type':'image/png'
  })

req.on('response', (res) ->
  if res.statusCode is 200
      console.log('saved to %s', req.url)
      socket.emit('upload success', imgurl: req.url)
  else
      console.log('error %d', req.statusCode)
  )

req.end(buf)

1
L'oggetto buffer genererà un errore "Buffer non definito", puoi darmi una soluzione per questo.
NaveenG

Ricevo anche lo stesso errore. hai una soluzione o no
Krishna

1
@NaveenG Questo è un esempio di nodo, forse stai usando un semplice JS?
Pointi

7

Ecco il codice di un articolo che ho trovato, pubblicato di seguito:

const imageUpload = async (base64) => {

  const AWS = require('aws-sdk');

  const { ACCESS_KEY_ID, SECRET_ACCESS_KEY, AWS_REGION, S3_BUCKET } = process.env;

  AWS.config.setPromisesDependency(require('bluebird'));
  AWS.config.update({ accessKeyId: ACCESS_KEY_ID, secretAccessKey: SECRET_ACCESS_KEY, region: AWS_REGION });

  const s3 = new AWS.S3();

  const base64Data = new Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64');

  const type = base64.split(';')[0].split('/')[1];

  const userId = 1;

  const params = {
    Bucket: S3_BUCKET,
    Key: `${userId}.${type}`, // type is not required
    Body: base64Data,
    ACL: 'public-read',
    ContentEncoding: 'base64', // required
    ContentType: `image/${type}` // required. Notice the back ticks
  }

  let location = '';
  let key = '';
  try {
    const { Location, Key } = await s3.upload(params).promise();
    location = Location;
    key = Key;
  } catch (error) {
  }

  console.log(location, key);

  return location;

}

module.exports = imageUpload;

Per saperne di più: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property

Crediti: https://medium.com/@mayneweb/upload-a-base64-image-data-from-nodejs-to-aws-s3-bucket-6c1bd945420f


4

La risposta accettata funziona alla grande, ma se qualcuno ha bisogno di accettare qualsiasi file anziché solo immagini, questa espressione regolare funziona alla grande:

/^data:.+;base64,/

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.