2012-04-05 13 views
13

Sto inviando il contenuto di questo modulo Flex (Non chiedere perché) al nodo. C'è un parametro post chiamato "foto" che è un'immagine codificata in base64.Node.js Base64 Decodifica e scrittura di immagini su file

Il contenuto della foto viene inviato su ok. Il problema è quando sto cercando di decodificare il contenuto e scriverlo su un file.

var fs = require("fs"); 

    fs.writeFile("arghhhh.jpg", new Buffer(request.body.photo, "base64").toString(), function(err) {}); 

Ho provato anche toString ("binario"). Ma sembra che il nodo non decodifichi tutto il contenuto. Sembra decodifica solo le informazioni dell'intestazione jpg e lascia il resto.

Qualcuno può aiutarmi per favore con questo?

Grazie

+0

Qual è foto qui ?? è quella immagine base64 ??? –

risposta

21

Rimuovere lo .toString() interamente e solo scrivere direttamente il buffer.

+0

ragazzo mi sento super stupido. Nathan, sei un eroe. Grazie. – Mehdi

+1

Piacere - felice di poter aiutare: D –

0

Rimuovere .toString()

Qui decodificare il base64 ad un buffer, che va bene, ma poi si converte il buffer in una stringa. Ciò significa che si tratta di un oggetto stringa i cui punti di codice sono byte del buffer.

8

questa è la mia soluzione completa che leggere qualsiasi formato di immagine Base64, decodificarlo e salvarlo nel formato corretto nel database:

// Save base64 image to disk 
    try 
    { 
     // Decoding base-64 image 
     // Source: http://stackoverflow.com/questions/20267939/nodejs-write-base64-image-file 
     function decodeBase64Image(dataString) 
     { 
      var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/); 
      var response = {}; 

      if (matches.length !== 3) 
      { 
      return new Error('Invalid input string'); 
      } 

      response.type = matches[1]; 
      response.data = new Buffer(matches[2], 'base64'); 

      return response; 
     } 

     // Regular expression for image type: 
     // This regular image extracts the "jpeg" from "image/jpeg" 
     var imageTypeRegularExpression  = /\/(.*?)$/;  

     // Generate random string 
     var crypto       = require('crypto'); 
     var seed       = crypto.randomBytes(20); 
     var uniqueSHA1String    = crypto 
               .createHash('sha1') 
               .update(seed) 
               .digest('hex'); 

     var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAZABkAAD/4Q3zaHR0cDovL25zLmFkb2JlLmN...'; 

     var imageBuffer      = decodeBase64Image(base64Data); 
     var userUploadedFeedMessagesLocation = '../img/upload/feed/'; 

     var uniqueRandomImageName   = 'image-' + uniqueSHA1String; 
     // This variable is actually an array which has 5 values, 
     // The [1] value is the real image extension 
     var imageTypeDetected    = imageBuffer 
               .type 
               .match(imageTypeRegularExpression); 

     var userUploadedImagePath   = userUploadedFeedMessagesLocation + 
               uniqueRandomImageName + 
               '.' + 
               imageTypeDetected[1]; 

     // Save decoded binary image to disk 
     try 
     { 
     require('fs').writeFile(userUploadedImagePath, imageBuffer.data, 
           function() 
           { 
            console.log('DEBUG - feed:message: Saved to disk image attached by user:', userUploadedImagePath); 
           }); 
     } 
     catch(error) 
     { 
      console.log('ERROR:', error); 
     } 

    } 
    catch(error) 
    { 
     console.log('ERROR:', error); 
    } 
+0

Hectic: D Nice work – James111

+0

Questa era la risposta che stavo cercando, grazie a m8 – Joniras