I just want to upload file in nodejs using multer. I am using postman to check whether file is doing upload or not. Everytime when I am trying to upload file through postman its showing me error. So below are the code what I have done so far.
my express.js file looks like this
/* ===================
Import Node Modules
=================== */
const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
const config = require('./database');
const path = require('path');
const appRoot = require('app-root-path') ;
const event = require('./routes/event.router');
const multer = require('multer');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = process.env.PORT || 8080; // Allows heroku to set port
mongoose.Promise = global.Promise;
process.env.NODE_ENV = 'devlopment';
// Database Connection
mongoose.connect(config.uri, {
useMongoClient: true,
}, (err) => {
// Check if database was able to connect
if (err) {
console.log('Could NOT connect to database: ', err); // Return error message
} else {
console.log('Connected to ' + config.db); // Return success message
}
});
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static(path.join(appRoot.path, 'dist')));
app.use('/event', event);
// Serve only the static files form the dist directory
app.get('*', (req, res) => {
res.sendFile(path.join(appRoot.path, 'dist/index.html'));
});
// Start Server: Listen on port 8080
app.listen(port, () => {
console.log('Listening on port ' + port + ' in ' + process.env.NODE_ENV + ' mode');
});
event.router.js looks like this
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
const Event = require('../../model/event.model');
var multer = require('multer');
var upload = multer({ dest: './public/uploads/img/',fileFilter:function(req,file,cb){
var ext = file.originalname.split('.').pop();
cb(null, file.fieldname + '-' + Date.now() + '.' + ext);
}
}).single('eventimage');
[![router.post('/', function(req, res, next) {
upload(req, res, function(err) {
console.log('file', req.file);
});
if( !req.file ) {
res.json({ success : false, message: 'You must provide event image!' });
}
else {
res.json({ success : true, message: req.file.eventimage });
}
});
Here is the screenshot for the postman
event.router.js
var express = require('express');
var multer = require('multer');
var route = express.Router();
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/')
},
filename: function (req, file, cb) {
console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
// cb(null, file.fieldname + '-' + Date.now() + '.' + extension);
cb(null, file.originalname + '-' + Date.now() + '.' + extension);
}
})
var upload = multer({ storage: storage }).single('avatar');
route.post('/', function (req, res) {
upload(req,res, function(err) {
if (err) {
res.send('error uploading file');
}
res.json({
success : true,
message : 'File uploaded!',
file : req.file
});
})
});
module.exports = route;
index.route.js
var fileUpload = require('../routes/fileUpload');
var express = require('express');
var route = express.Router();
route.use('/upload', fileUpload);
module.exports = route;
Now include this index.route.js in your index.js file/app.js file what ever name you have kept.
Don't forget to install all dependencies.
And when uploading image see the name given in .single(), in my case i have written avatar.
See the attachments how to browse your file and what is to be set in headers.
Related
Im trying to upload images with multer. Everything has worked before on localhost fine. Images get uploaded and i can view them from the url link the code provides. However once i have uploaded it on a server im starting to get this error : "Cannot GET /marketplace-api/rest-api/image/1650484814178.jpg".
I have not provided link to server/domains to the question in case people say thats the problem.
Here is my code:
const express = require('express');
const app = express();
const multer = require("multer");
const path = require("path");
const db = require('./db');
const cors = require('cors');
const port = 5000;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true , limit: '50mb'}));
app.use(cors());
app.use("/image", express.static("image"));
let imageName = "";
const storage = multer.diskStorage({
destination: path.join("./image"),
filename: function (req, file, cb) {
imageName = Date.now() + path.extname(file.originalname);
cb(null, imageName);
},
});
const upload = multer({
storage: storage,
limits: { fileSize: 3000000 },
}).single("myImage");
app.post("/marketplace-api/rest-api/upload-image", (req, res) => {
upload(req, res, (err) => {
if (err) {
console.log(err);
} else {
return res.status(201)
.json({ url: "http://link to domains/marketplace-api/rest-api/image/" + imageName });
}
});
});
app.listen(port, () => {
console.log("server run in port", port);
});
ok, few things, 1. you dont have any get functions, which means you cant post to this location, i suggest doing this:
app.get('/', (req, res) => {
res.sendFile(__dirname + "/index.html");
});
and create a file called index.html, go on your site (localhost), and it should work, after that add a form in the html file, it should look something like this
<form action = "/marketplace-api/rest-api/upload-image" method = "POST">
<input type = "file" name="image">
<input type = "submit">
</form>
this will add a basic form where you can upload your photo.
there are a few more stuff to add / change, i will fix everything and make it a repo then send it here
Problem:
Trying to get json string but req.body in the post data handler returns undefined. Is it even possible to send json and file in one post request to the server?
Code:
Data sended to the server:
function saveFile(e) {
let info = {titleI: title.value, dirI: dir.value};
let xhr = new XMLHttpRequest();
let formData = new FormData();
let file = e;
formData.append("info", JSON.stringify(info));
formData.append("file", file);
xhr.onreadystatechange = state => { console.log(xhr.status); }
xhr.timeout = 5000;
xhr.open("POST", '/register');
xhr.send(formData);
}
The post data handler:
router.post("/", (req, res) => {
console.log(req.body.info)
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
let dirName = "a"
fs.mkdir("D:/node website/ipgrabber/files/"+dirName+"/", function(err) {
if (err) {
console.log(err)
}
})
fstream = fs.createWriteStream("D:/node website/ipgrabber/files/"+dirName+"/" + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
})
This is the main class:
var express = require('express')
var http = require('http')
const mongoose = require('mongoose')
const { json } = require('express')
var cookieParser = require('cookie-parser')
var app = express()
var server = http.createServer(app)
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}));
var busboy = require('connect-busboy');
app.use(busboy());
//error handler
mongoose.connect('mongodb://localhost:27017/grabber', {useNewUrlParser: true, useUnifiedTopology: true});
app.use(cookieParser())
app.set("view engine", "ejs")
app.set('views', __dirname+'/views/html/');
app.use("/js", express.static(__dirname + "/views/js"))
app.use("/css", express.static(__dirname + "/views/css"))
const registerRoute = require("./routes/register")
const grabberRoute = require("./routes/grabber")
app.use("/register", registerRoute)
app.use("/id", grabberRoute)
app.get("/", (req, res) => {
res.redirect("/register")
})
app.use(function (err, req, res, next) {
res.status(400).send("Error code: 2 <hr> This page is currently inaccessible! <br> <a href='/'>GO TO HOMEPAGE</a>")
console.log(err)
})
server.listen(80)
Project resources:
body-parser - 1.19.0
connect-busboy - 0.0.2
cookie-parser - 1.4.5
crypto-js 4.0.0
ejs 3.1.5
express 4.17.1
mongoose 5.11.19
By default, express can't manage to get multipart/form-data correctly.
You have to use a middleware to handle and parse this request.
I recommend to use multer.
In your case, you're using connect-busboy so the info should be handled like this:
req.busboy.on('field', function(key, value, keyTruncated, valueTruncated) {
console.log('your info is here', key, value);
});
I am looking to start including my route files in my Node.js and express application. However, when I require the local route files into my server.js file, and try to run that on Nginx, I get a 502 Bad Gateway error.
The code that is giving me trouble is currently commented out. Any ideas on what might be causing this performance?
server.js
require('dotenv').config();
const express = require('express');
const bodyparser = require('body-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
// const oidc = require('./okta');
// const searchRouter = require('./routes/search');
// const inputRouter = require('./routes/input');
// const dataRouter = require('./routes/view-all');
const app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/views/index.html');
});
app.get('/page', function(req, res) {
res.render(__dirname + '/views/optishop.ejs');
});
const listener = app.listen(8080, function() {
console.log('Your app is listening on port ' + listener.address().port);
});
Edit: This is the file being required in the searchRouter declaration.
search.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const oidc = require('../okta');
const router = express.Router();
router.post('/search', oidc.ensureAuthenticated(), async (req, res) => {
await MongoClient.connect(
process.env.MONGODB_URI,
{ useUnifiedTopology: true },
async (err, client) => {
assert.equal(null, err);
const db = client.db('test');
const arr = req.body.item.trim().split(/; */gi);
const user = req.session.passport.user.userinfo.sub;
const cursor = await db
.collection('test')
.find({
user
})
.toArray();
const filteredCursor = cursor.filter(obj => {
return arr.includes(obj.item);
});
res.render('index', {
cursor: filteredCursor
});
// res.send(filteredCursor);
client.close();
}
);
});
module.exports = router;
I want to delete Folder/File in client side (Using javascript/Jquery/AngularJS1). I was Searching, finally i got using Node.js it can be done in Sitepoint link. Now iam not getting how to set up Node.js fs(File System) with either of the language.(Prefered language is AngularJS1). Looking for solution.
Thanks in advance.
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('*', function (req, res) {
console.log(req.path);
var path = req.path;
if(req.path == '/'){
res.sendFile( __dirname + "/" + "index.html" );
}else
{
res.sendFile( __dirname + req.path);
}
});
app.post('/app',function (req, res) {
console.log(req.body)
var action = req.body.action;
var data = req.body.data;
var fname = req.body.fileName;
switch(action) {
case 'upLoad':
function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
response = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');
return response;
};
var imageBuffer = decodeBase64Image(data);
var newPath = __dirname + "/app/images/" + fname;
fs.writeFile(newPath, imageBuffer.data, function(err) {
res.send({confirm : "uploaded" , filename:fname });
});
default:
}
})
var server = app.listen(8080, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Hi this is Application Folder which i had used.
In this Server.js file where i included node.js modules and load the application.
i'm just a beginner in node.js
i'll try to make a site with xpress, so I can upload anything on there.
i set the server locally on my mac.
it is the code that I'd writen
server.js
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multers = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multers({ dest: '/public/'}));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
and these are the error messages
node upload.js
/Users/dayatura/Documents/node/node_modules/express/lib/application.js:209
throw new TypeError('app.use() requires middleware functions');
^
TypeError: app.use() requires middleware functions
at EventEmitter.use (/Users/dayatura/Documents/node/node_modules/express/lib/application.js:209:11)
at Object. (/Users/dayatura/Documents/node/upload.js:10:5)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
anyone help please :)
These are the issues:
var multer = require('multer')(({ dest: '/public/'}));
Then you can use it this way.
app.post('/upload', multer.single('image'), function(req, res,next){
//Handle image content here.
console.log(req.file); //to access file
});
multer is meant to be used in the following way, per the docs:
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
Documentation regarding how to use any of the multer methods: https://github.com/expressjs/multer#usage
I have just studied multer examples from above links.
Js
var express = require('express');
var app = express();
var fs = require("fs");
var multers = require('multer');
var upload = multers({ dest: '/public/'});
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/file_upload', upload.array('avatar'), function (req, res) {
for (var i = 0, len = req.files.length; i < len; i++) {
var mainFile = req.files[i];
var file = __dirname + "/" + mainFile.name;
fs.readFile( mainFile.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message :'File uploaded successfully',
filename: mainFile.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
}
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
this is complete code to upload files using multer :
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/app/product') /* here you define destination of uploaded files*/
},
filename: function (req, file, cb) {
var ext=file.originalname.split(".")
cb(null, Date.now() +'.'+ext[1]) /* here you set extensions of files when uploaded */
}
})
var upload = multer({ storage: storage });
/* upload.any() method upload any files */
app.post('/backend/product/edit/:id',upload.any(),function (req, res) {
/* req.files are all files that uploaded to server */
/* you can see them use res.json(req.files) */
})