I am not able to upload the file using Connect framework. I have refered the link Connect . Below is my code
app.use(connectDomain())
.use(connectRoute(function (router) {
router.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(JSON.stringify({fields: fields, files: files}));
});
I am getting always the response as below
received upload:
{"fields":{},"files":{}}
example given in formidable module..
var files = [],
fields = [];
form
.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function() {
console.log('-> upload done');
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(files));
});
form.parse(req);
Related
app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
try{
if (files.file.name != '') {
file_newname = dt.MD5(files.file.name + Date() + Math.random()) + '.jpg' + ;
var file_newpath = './tmp/' + file_newname;
fs.readFile(file_oldpath, function (err, data) {
// Write the file
fs.writeFile(file_newpath, data, function (err) {
console.log('File written!');
res.end(JSON.stringify({
message: 'file uploaded successfully'
}));
});
});
}
}catch (e) {
}
});
});
The single image upload is working perfectly.I tried the following code
var form = new formidable.IncomingForm();
files = [],
fields = [];
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
console.log(file.name);
files.push([field, file]);
})
form.on('end', function() {
console.log('done');
//res.redirect('/forms');
});
form.parse(req);
But only a single image gets uploaded. i m using react in frontend. Node and express in backend.
I also tried multer. But that doesnt working
app.post('/getrast', upload.array('files'), function (req, res) {
res.json({data: req.files});
});
Use the multiple flag with the incoming form with true as value.
var form = new formidable.IncomingForm();
form.multiples = true; //use this while dealing with multiple files
files = [],
fields = [];
form.on('field', function(field, value) {
fields.push([field, value]);
})
form.on('file', function(field, file) {
fs.rename('add your logic here for renaming files'); // rename it here
console.log(file.name);
files.push([field, file]);
})
form.on('end', function() {
console.log('done');
//res.redirect('/forms');
});
form.parse(req);
I got problem that i cant get this code to save to image in a img tag. the picture will only show the first time i enter the site, the next time i enter the site it is gone. guess its the pipe but is there a way to keep it there? have searched for days now...
this is my code to save it and get it.
router.post('/', function(req, res, next) {
var busboy = new Busboy({ headers : req.headers });
var fileId = new mongo.ObjectId();
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
console.log('got file', filename, mimetype, encoding);
var writeStream = gfs.createWriteStream({
_id: fileId,
filename: filename,
mode: 'w',
content_type: mimetype,
});
file.pipe(writeStream);
}).on('finish', function() {
// show a link to the uploaded file
res.writeHead(200, {'content-type': 'text/html'});
res.end('blogginnlegg1');
});
req.pipe(busboy);
});
//get file?
router.get('/file/:id', function(req, res, next){
gfs.findOne({ _id: req.params.id }, function (err, file) {
if (err) return res.status(400).send(err);
if (!file) return res.status(404).send('');
res.set('Content-Type', file.contentType);
res.set('Content-Disposition', 'attachment; filename="' + file.filename + '"');
var readstream = gfs.createReadStream({
_id: file._id
});
readstream.on("error", function(err) {
console.log("Got error while processing stream " + err.message);
res.end();
});
readstream.pipe(res);
});
});
I have the next code:
router.post('/subirArchivo', function (req, res){
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin', function (name, file){
file.path = path.join(__dirname,'../../../../uploads/', file.name);
});
form.on('file', function (name, file){
console.log('Uploaded ' + file.name);
});
res.sendFile(path.join(__dirname,'../../../client/views/faseVinculacion', 'busquedaVinculacion.html'))
Upload the file it's fine, but, how create a new folder that not exists?
First you need to add fs-extra (easier way)
and in your post, add:
fs.mkdirsSync(__dirname + '/../public/dist');
form.uploadDir = __dirname + '/../public/dist';
more details:
if (req.url == '/upload') {
var form = new formidable.IncomingForm(),
files = [],
fields = [];
fs.mkdirsSync(__dirname + '/../public/dist');
form.uploadDir = __dirname + '/../public/dist';
form
.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function() {
console.log('-> upload done');
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received fields:\n\n '+util.inspect(fields));
res.write('\n\n');
res.end('received files:\n\n '+util.inspect(files));
});
form.parse(req);
}
I would like to move a small image from one server to another (both running node). As I search, I haven't found enough. This post remains unanswered.
As I started experimenting I wrote the following to the first server :
app.post("/move_img", function(req, res) {
console.log("post handled");
fs.readFile(__dirname + "/img_to_move.jpg", function(err, data) {
if (err) throw err;
console.log(data);
needle.post(server2 + "/post_img", {
data: data,
name : "test.jpg"
}, function(result) {
console.log(result);
res.send("ok");
});
});
});
This part seems to be working as I could be writing the data in the same server (using fs.writeFile) recreate the img.
Now as I am trying to handle the post in the other server I have a problem.
Server2:
app.post('/post_img', [ multer({ dest: './uploads/images'}), function(req, res) {
console.log("body ",req.body) // form fields
console.log("files ",req.files) // form files
res.send("got it");
}]);
This way i get an empty object in the files and the following in the body: { 'headers[Content-Type]': 'application/x-www-form-urlencoded', 'headers[Content-Length]': '45009' }
I think I could use busboy as an alternative but I can't make it to work. Any advice, tutorial would be welcome.
I solved my problem by using the following code,
server1 (using needle) :
app.post("/move_img", function(req, res) {
console.log("post handled")
var data = {
image:{
file: __dirname + "/img_to_move.jpg",
content_type: "image/jpeg"}
}
needle.post(server2 + "/post_img", data, {
multipart: true
}, function(err,result) {
console.log("result", result.body);
});
})
Server 2:
app.use('/post_img',multer({
dest: '.uploads/images',
rename: function(fieldname, filename) {
return filename;
},
onFileUploadStart: function(file) {
console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function(file) {
console.log(file.fieldname + ' uploaded to ' + file.path)
}
}));
app.post('/post_img', function(req, res) {
console.log(req.files);
res.send("File uploaded.");
});
An alternative for the server 1 is the following (using form-data module):
var form = new FormData();
form.append('name', 'imgTest.jpg');
form.append('my_file', fs.createReadStream(__dirname + "/img_to_move.jpg"));
form.submit(frontend + "/post_img", function(err, result) {
// res – response object (http.IncomingMessage) //
console.log(result);
});
I'd simply read your file from the first server with the function readFile() and then write it to the other server with the function writeFile().
Here you can see use of both functions in one of my servers.
'use strict';
const express = require('express');
const multer= require('multer');
const concat = require('concat-stream');
const request = require('request');
const router = express.Router();
function HttpRelay (opts) {}
HttpRelay.prototype._handleFile = function _handleFile (req, file, cb) {
file.stream.pipe(concat({ encoding: 'buffer' }, function (data) {
const r = request.post('/Endpoint you want to upload file', function (err, resp, body) {
if (err) return cb(err);
req.relayresponse=body;
cb(null, {});
});
const form = r.form();
form.append('uploaded_file', data, {
filename: file.originalname,
contentType: file.mimetype
});
}))
};
HttpRelay.prototype._removeFile = function _removeFile (req, file, cb) {
console.log('hello');
cb(null);
};
const relayUpload = multer({ storage: new HttpRelay() }).any();
router.post('/uploadMsgFile', function(req, res) {
relayUpload(req, res, function(err) {
res.send(req.relayresponse);
});
});
module.exports = router;
see multer does all the tricks for you.
you just have to make sure you use no middle-ware but multer to upload files in your node starting point.
Hope it does the tricks for you also.
Here is my code:
var http = require('http')
http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "json"
});
fs.readdir('.', function (error, files) {
if (error)
res.end(util.format(error))
files.forEach(function (file) {
fs.stat(file, function (erro, stats) {
console.log(JSON.stringify(stats))
res.write(JSON.stringify(stats))
})
})
})
}).listen(3000);
console.log("server is running!")
When i visit http://127.0.0.1:3000/, there is no output, but the console output is:
{"dev":0,"mode":16822,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":0,"atime":"2014-11-20T13:36:19.000Z","mtime":"2014-11-20T13:36:19.000Z","ctime":"2014-11-20T13:31:53.000Z"}
{"dev":0,"mode":33206,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":11,"atime":"2014-11-20T13:56:21.000Z","mtime":"2014-11-20T13:56:21.000Z","ctime":"2014-11-20T13:56:21.000Z"}
{"dev":0,"mode":33206,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":844,"atime":"2014-11-20T14:24:04.000Z","mtime":"2014-11-20T14:24:04.000Z","ctime":"2014-11-20T13:32:19.000Z"}
{"dev":0,"mode":16822,"nlink":1,"uid":0,"gid":0,"rdev":0,"ino":0,"size":0,"atime":"2014-11-20T14:03:56.000Z","mtime":"2014-11-20T14:03:56.000Z","ctime":"2014-11-20T13:56:21.000Z"}
You need to call res.end() when you're done with your res.write calls.
http.createServer(function (req, res) {
res.writeHead(200, {
"Content-Type": "json"
});
fs.readdir('.', function (error, files) {
if (error)
res.end(util.format(error))
var filesLeft = files.length;
files.forEach(function (file) {
fs.stat(file, function (erro, stats) {
console.log(JSON.stringify(stats))
res.write(JSON.stringify(stats))
// Keep track of how many files' fs.stat calls are left
if (--filesLeft === 0) {
res.end();
}
})
})
})
}).listen(3000);