0
I’m starting now with Nodejs, and I’m testing an example that saves data along with an upload of images.
It’s working, but the image is duplicated.
I wish I knew where the mistake was 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
tmp\19ac6310c0d101cb280f1f9bbfe1bfb0
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!
You can add the code of the uploading client ?
– Ivan Vilanculo
@Ivanvilanculo included!
– Guilherme Lirio
I am not a guru in Node js but tell me, how many times the log
console.log(req.file.originalname);
appears on your console?– Ivan Vilanculo
Appears only once. I will include the log.
– Guilherme Lirio
OK I’d appreciate it! But I’ll try to replicate it on my machine as soon as I get home!
– Ivan Vilanculo
I found the error: app.use(multer({dest:'/tmp/'}).single('file')); Lacked the bar before/tmp/ and after, but wanted to know why! =/
– Guilherme Lirio