2015-03-03 21 views
20

Sto provando a leggere un'immagine dal lato client codificata in base64. Come leggere con nodejs?ReadFile in Base64 Nodejs

Il mio codice:

// add to buffer base64 image 
var encondedImage = new Buffer(image.name, 'base64'); 

fs.readFile(encondedImage, "base64", function(err, buffer){ 
    if (err) { 
     console.log('In read file') 
     console.log(err) 
    } else { 
     // check err 
     lwip.open(buffer, 'jpg', function(err, image){ 
      console.log('in open') 
      if (err) console.log(err) 

      if (image) console.log(image) 
      // check 'err'. use 'image'. 
      // image.resize(...), etc. 
     }); 
    } 
}) 

Ma, ho ottenuto questo errore:

In read file 
[Error: Path must be a string without null bytes.] 

* * SOLUZIONE

lwip accetta buffer nel metodo aperto.

// add to buffer base64 image from step 
var encondedImage = new Buffer(image.name, 'base64'); 

// check err 
lwip.open(encondedImage, 'jpg', function(err, image){ 
    // image.resize(..), etc 
}); 
+1

'fs.readFile' prende una stringa come primo discussione. Stai provando a passargli un 'Buffer'. – cubrr

risposta

49

Penso che il seguente esempio dimostra quello che vi serve: http://www.hacksparrow.com/base64-encoding-decoding-in-node-js.html

L'essenza di questo articolo è questa parte di codice:

var fs = require('fs'); 

// function to encode file data to base64 encoded string 
function base64_encode(file) { 
    // read binary data 
    var bitmap = fs.readFileSync(file); 
    // convert binary data to base64 encoded string 
    return new Buffer(bitmap).toString('base64'); 
} 

// function to create file from base64 encoded string 
function base64_decode(base64str, file) { 
    // create buffer object from base64 encoded string, it is important to tell the constructor that the string is base64 encoded 
    var bitmap = new Buffer(base64str, 'base64'); 
    // write buffer to file 
    fs.writeFileSync(file, bitmap); 
    console.log('******** File created from base64 encoded string ********'); 
} 

// convert image to base64 encoded string 
var base64str = base64_encode('kitten.jpg'); 
console.log(base64str); 
// convert base64 string back to image 
base64_decode(base64str, 'copy.jpg'); 
+1

Sebbene questo collegamento possa rispondere alla domanda, è meglio includere qui le parti essenziali della risposta e fornire il link per riferimento. Le risposte di solo collegamento possono diventare non valide se la pagina collegata cambia. –

+1

Grazie per la tua spiegazione. Ora capisco perché sto ottenendo i downvotes. – Sjoerd

+0

Ho ottenuto il buffer è errore non definito. Mi manca qualche libreria js o qualcos'altro – Krishna