app.post('/file_upload', function (req, res) {
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '/uploads');
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);
});
UI used to upload multiple images in nodejs using formidable
The files are being creating. But the images are getting saved without extension.
Is there anything extra steps i have to do?
This worked for me:
form.keepExtensions = true;
Try onPart:
form.on('part', function (part) {
if (part.filename) {
if (!isInvalidFileName(part.filename) || !isInvalidMimeType(part.mime)) {
files.push([part]);
}
}
})
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 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.
I am creating a node server to upload files using 'express','fs' and 'busboy' module. The server is working as expected but when I cancel the upload before complete, the incomplete file is stored in the filesystem. How can I remove the incomplete file?
var express = require("express"),
fs = require("fs"),
Busboy = require("busboy");
app = express();
app.listen(7000);
app.get("/", display_form);
app.post("/upload", function(req, res) {
var busboy = new Busboy({
headers: req.headers
});
busboy.on("file", function(fieldname, file, filename, encoding, mime) {
var fstream = fs.createWriteStream("./uploads/" + filename);
file.pipe(fstream);
file.on("data", function(chunk) {
console.log(chunk.length);
});
file.on("end", function() {
console("end");
});
fstream.on("close", function() {
fstream.close();
console("fstream close");
});
fstream.on("error", function() {
console("fstream error ");
});
});
busboy.on("finish", function() {
console.log("uploaded");
res.send("file uploaded");
});
busboy.on("error", function() {
console("error busboy");
});
req.pipe(busboy);
});
Thanks for your help and I finally I found a way to this problem. I added under mentioned code snippet and its working fine.
req.on("close", function(err) {
fstream.end();
fs.unlink('./uploads/' + name);
console.log("req aborted by client");
});
I don't know busboy, but you open a stream and never close it.
Why don't you exploit the stream and filename to 'finish' and 'error' and act accordingly?
Example:
busboy.on('error', function() {
fs.unlink('./uploads/' + filename);
console.log('error busboy');
}
i want to develope and application in node.js where i shud b able to upload a video in my page and store a link to that video in database(mongodb).when i click //to the link the vedio should get displayed.also i shud b able to display all the //video's uploaded in the page.I tried to code to upload phot
//new show photo code
app.get('/photos', function(req, res) {
photos.list(function(err, photo_list) {
res.render('photos/index', {locals : {
photos: photo_list
}});
});
});
app.get('/photos/new', function(req, res){
res.render('photos/new', {
locals: {
title: 'New File Upload'
}
});
});
app.post('/photos', function(req, res) {
req.setEncoding('binary');
var parser = multipart.parser();
parser.headers = req.headers;
var ws;
parser.onpartBegin = function(part) {
consol.log('inside begin');
ws = fs.createWriteStream(__dirname + '/static/upload/photos.' + part.filename)
ws.on('error', function(err) {
throw err;
});
};
parser.onData = function(data) {
ws.write(data);
};
parser.onPartEnd = function() {
ws.end();
parser.close();
console.log('file successfully uploaded');
res.redirect('/photos');
};
req.on('data', function(data) {
console.log('shud not go here');
parser.write(data);
});
});
//can any one send me the code for the same or else find were i am doing //wrong.....answer immediately required....
You should use formidable for file uploads in Node.js, it's a widely used library for such a thing.