I want to send a file with express-busboy. On the readme it says that you can use req.body. So i did. The regular inputs worked, but the file inputs just returned the name of the file i uploaded. I uploaded the file called myfile.png and in the textinput, i put the value of 'Hello World'. I want the send the file that i upload to a folder called mydir (which is in ./). Here is a sample of code:
//js:
const express = require('express');
const mysql = require('mysql');
const bp = require('body-parser');
const session = require('express-session');
const uc = require('upper-case');
const busboy = require('express-busboy');
const fs = require('fs');
const util = require('util');
const app = express();
app.use(bp.urlencoded({ extended: true }));
busboy.extend(app, {
upload: true,
path: './mydir'
});
app.post('/somewhere', (req, res) => {
console.log(req.body.textinput);
//returns the 'Hello World'
console.log(req.body.imginput);
//returns 'myfile.png'
});
<html>
<body>
<form action="/somewhere" method="post" enctype="multipart/form-data">
<input type="text" name="textinput">
<input type="file" name="imginput" accept='image/*'>
</form>
</body>
</html>
Related
How do I post a value which is on the client-side and get it on the server-side.
example:
<form action="/myform" method="POST">
<input type="text" name="mytext" required />
<input type="submit" value="Submit" />
</form>
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.get('/myform', function(req, res){
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
app.listen(3000)
<form action="http://127.0.0.1:3000/myform" method="post">
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myform', function(req, res) {
var myText = req.body.mytext; //mytext is the name of your input box
res.send('Your Text:' +myText);
});
Your code seems to be fine, apart from wrong method name. In HTML form you have mentioned POST method but at server you are listening to GET method. So just change, app.get('/myform', to app.post('/myform',.
It should work.
I have question.I've looked at some questions here, but I can't get the answer.My question is, I want to upload and read a json file, I try with "multer" but couldn't.So I want to put the file I upload to the result variable. Can you help me? How can I achieve this?
HTML;
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<form action="/import" enctype="multipart/form-data" method="post">
<input type="file" name="filename">
<input type="submit" value="Upload">
</form>
</body>
</html>
Server.js
const express = require('express');
const multer = require('multer');
const upload = multer({
dest: 'uploads/' // "uploads"
});
const app = express();
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
route.post("/import", upload.single("filename") (req, res, next) => {
var result = require(# I want to send the json file I uploaded here, and I need to see the contents of the json file as is #)
res.json(result)
res.redirect("/")
});
app.listen(3000);
The upload.single() parses the data stream and saves as a file based on the configuration. In your case, it will look for filename field in the incoming request and save the file in the uploads/ folder. The metadata of the file is available in req.file object. You can simply do console.log(req.file) to see the information.
To read the content of the file, you can use req.file.path field. Here is how:
const fs = require("fs");
const path = require("path");
/** In the controller */
const absolutePath = path.join(__dirname, req.file.path);
const jsonString = fs.readFileSync(absolutePath, "utf-8");
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
Here is how the complete server.js would look like:
const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const upload = multer({
dest: "uploads/" // "uploads"
});
const app = express();
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
const route = express.Router();
route.post("/import", upload.single("filename"), (req, res, next) => {
console.log(req.file);
const absolutePath = path.join(__dirname, req.file.path);
const jsonString = fs.readFileSync(absolutePath, "utf-8");
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
res.redirect("/");
});
app.use(route);
app.listen(3000);
I have added some parts which were missing from your snippet ( like express.Router ). They might be different though.
I'm trying a simple form submission code, and I'm using post method.
My server.js code
//N-4E;V-56;I-49
//var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var idx = require('./index.js');
var ra = require('./ra.js');
var app = express();
app.engine('html',require('ejs').renderFile);
app.set('view engine', 'html');
app.set('port',process.env.PORT || 5649);
app.use(bodyParser.urlencoded({extended: true}));
app.use('/',idx);
app.use('/reg_path',ra);
app.listen(app.get('port'),function(){
console.log('Express started press asdfadsfasdfasdf');
});
my index.js
var express = require('express');
var fs = require('fs');
var router = express.Router();
router.get('/',function(req,res,next){
//res.sendHeader(.)
res.render('index.ejs',{});
//res.render('title.ejs',{});
});
module.exports = router;
my index.ejs
<!DOCTYPE html>
<html>
<head>
</head>
</body>
<div id="reg_path">
<p>Enter the Regressions Folder Path</p>
<form action="/reg_path" method="post" enctype="multipart/form-data">
<fieldset>
<label for="path">Path:</label>
<input type="text" id="path" name="path" placeholder="Enter the Absolute path"/>
<input type="submit" value="Enter"/>
</fieldset>
</form>
</div>
</body>
</html>
my ra.js is
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var app = express.Router();
var path;
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post("/",function(req,res){
console.log(req.body.path);
path = req.body.path;
fs.access('path',fs.constants.F_OK, (err) => {
if (err) throw err;
res.redirect('./index');
//if (err) {
// res.writeHead(404,{'Content-Type':'text/plain'});
// return res.end('The specified path "' + path + '" does not exists');
//}
});
//fs.access('path',fs.constants.R_OK, (err) => {
// //if (err) {
// // res.writeHead(404,{'Content-Type':'text/plain'});
// // return res.end('The specified path "' + path + '" has no READ permissions');
// //}
//});
});
module.exports = app;
Now, from the index page, when I type a path in the form, and press the submit, in the console.log the 'req.body' is returned as 'undefined'.
most of the code in ra.js is commented or not updated because the 'req.body' value is unavailable in the first place. I need to correct it first.
I've searched through internet to try and figure out the mistake that is in my code, but to my vain I'm unable to uncover it. Any help is much appreciated
node version:v6.11.0
body-parser :1.17.2
express :4.15.3
ejs :2.5.6
Your form uses enctype="multipart/form-data" which is an encoding type that body-parser doesn't support.
If you need to use this type (for instance, if you're going to be uploading files from your form), take a look at multer.
Otherwise, leave out the enctype attribute so the form will default to application/x-www-form-urlencoded.
I am using multer module to upload files to my application with a multiform-data enctype on my form. However, I have tried all possible solutions I have found to upload the file in vain. I am receiving always a "Cannot read property path of undefined or file of undefined. Here below is my view, controller and config files, anyone can help point was it wrong?
View
<form method="post" action="/images" enctype="multipart/form-data">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label for="file" class="col-sm-2 control-label">Browse:</label>
<div class="col-md-10">
<input type="file" name="file" id="file" class="form-control">
</div>
</div>
controller:
var tempPath = req.files.path;
var ext = path.extname(req.files.name).toLowerCase();
var finalPath = path.resolve('./public/upload' + imageUrl + ext);
config file:
var path = require('path');
var express = require('express');
var routes = require('./routes'); //routes for GET, POST...requests
var exphbs = require('express-handlebars'); //templating engine
//var bodyParser = require('body-parser'); //form submission request are accessible with req.body
var cookieParser = require('cookie-parser'); //cookies to be send and received
var morgan = require('morgan'); //module for logging - used in debugging
var methodOverride = require('method-override'); //for older browser to fake REST verbs
var errorHandler = require('errorhandler'); //handles error through the middleware
var moment = require('moment'); //npm module to handle dates formating
var multer = require('multer'); //to handle file uploading
module.exports = function(app) {
app.use(morgan('dev'));
//app.use(multer({dest: path.join(__dirname, 'public/upload/temp')})); //proper use of multer
app.use(multer({ dest: path.join(__dirname,'public/upload/temp')}).any());
app.use(methodOverride());
app.use(cookieParser('IciCestParis'));
routes(app); //moving the routes to route folder
app.use('/public/', express.static(path.join(__dirname,'../public')));
I want to display names of all files.
Here is my code:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/nodejs/diwanjidocs/tmp/'}).array('files'));
app.post('/file_upload', function (req, res) {
console.log(req.files);
for(var i=0;i<req.files.length;i++){
console.log(req.files.name);
}
})
var server = app.listen(8081,'localhost',function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
For single file upload req.file.originalname returns filename but for multiple files how to get file names ?
req.files.forEach(function (file) {
console.log(file.originalname)
});
That depends on your form, but consinder the following form:
<form action="/uploadFiles" method="post" enctype="multipart/form-data">
<input type="file" multiple="multiple" accept="image/*" name="uploadedImages"/><br/>
<input type="submit" value="Upload" />
</form>
Then to handle the form you will include the:
app.use(express.bodyParser());
And then you can manipulate the file array:
req.files.uploadedImages.forEach(function(photo, index, array) {
console.log(photo.name);
});