2016-11-21 1 views
1

Ich habe ein CMS für ein Lebensmittel-Automatisierungssystem, und ich werde ein Teil für das Hochladen Bilder für Lebensmittel hinzuzufügen:Wie kann ich ein Bild mit nodejs hochladen und ausdrücken?

<form method="post" enctype="multipart/form-data" action="/upload"> 
    <td><input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file"></td> 
    <td><input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" ></td> 
</form> 

Ich schrieb für die Herstellung einer POST-Anfrage in Express.js diesen Code:

app.post('/upload', function (req, res) { 
    var tempPath = req.files.file.path, 
     targetPath = path.resolve('./uploads/image.png'); 
    if (path.extname(req.files.file.name).toLowerCase() === '.png') { 
     fs.rename(tempPath, targetPath, function(err) { 
      if (err) 
       throw err; 
      console.log("Upload completed!"); 
     }); 
    } else { 
     fs.unlink(tempPath, function() { 
      if (err) 
       throw err; 
      console.error("Only .png files are allowed!"); 
     }); 
    } 
}); 

aber wenn ich diese app.use definieren, bekomme ich einen Fehler:

Middleware: app.use(express.bodyParser({uploadDir:'/img'}));
Error: Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware .

wenn ich eine Middleware wie folgt definieren:

app.use(bodyParser({uploadDir:'/img/'})); 

Ich habe keine Fehler, aber mein Code funktioniert nicht richtig.

+1

1. Ihre Frage Titel hat nichts mit Ihrer Frage zu tun - 2. Verwenden Sie https: // www .npmjs.com/package/multer –

+1

Auch Ihr HTML ist ungültig - 'td' kann nur ein Kind eines' tr' sein –

+0

@ChrisG tnnnnnnx –

Antwort

0

Diese Lösung für mich gearbeitet:

multer = require('multer'), 
upload = multer({ dest: 'views/img' }); 




app.post('/upload',upload.single('file'), function (req, res) { 

}); 

Und meine Form HTML Form:

<form method="post" enctype="multipart/form-data" action="/upload"> 
    <input class="styleFormForAddProducts foodpicForAddFood" type="file" name="file"> 
    <input class="styleFormForAddProducts submitForAddFood" type="submit" value="Submit" > 
</form> 
Verwandte Themen