I'm starting now with NodeJS, and I'm testing an example that saves data along with an image upload.
It is working, but the image is duplicated.
I wanted to know where the error is, and why:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({dest:'tmp'}).single('file'));
app.get('/', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/process_post', function (req, res) {
console.log(req.file.originalname);
console.log(req.file.path);
console.log(req.file.mimetype);
console.log('-----------');
console.log(req.file);
var file = __dirname + "/tmp/" + req.file.filename + '.jpg';
fs.readFile(req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'Arquivo enviado com sucesso!',
filename:req.file.filename + '.jpg',
first_name:req.body.first_name,
last_name:req.body.last_name
};
}
console.log( response );
res.end(JSON.stringify( response ));
});
});
})
var server = app.listen(8081, function () {
var port = server.address().port
console.log("Servidor iniciado em http://localhost:%s", port)
})
HTML:
<form action = "http://127.0.0.1:8081/process_post" method = "POST" enctype = "multipart/form-data">
First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name"> <br>
Foto: <input type="file" name="file" size="50" /> <br>
<input type = "submit" value = "Submit">
</form>
CONSOLE.LOG
C_OURO.png
tmpac6310c0d101cb280f1f9bbfe1bfb0
image/png
-----------
{ fieldname: 'file',
originalname: 'C_OURO.png',
encoding: '7bit',
mimetype: 'image/png',
destination: 'tmp',
filename: '19ac6310c0d101cb280f1f9bbfe1bfb0',
path: 'tmp\19ac6310c0d101cb280f1f9bbfe1bfb0',
size: 5555562 }
{ message: 'Arquivo enviado com sucesso!',
filename: '19ac6310c0d101cb280f1f9bbfe1bfb0.jpg',
first_name: 'Nome',
last_name: 'Sobrenome' }
Thank you!