<form action="http://localhost:3000/examples" method="post" enctype="multipart/form-data" accept="application/json">
<input type="text" name ="name">
<input type="text" name ="codedescription">
<input type="file" name ="file">
<input type="submit" value="Upload selected file to server">
</form>
var multer = require('multer');
app.use(multer({ dest: './uploads/',
onFileUploadStart : function(file){
console.log('File recieved:');
console.log(file);
},
onFileUploadData:function (file,data){
console.log('Data recieved');
},
onParseEnd: function(req,next){
next();
}
}));
app.route('/examples').post(users.requiresLogin, examples.create);
exports.create = function(req, res) {
console.log("req.files"+req.files);
console.log("req.name"+req.body.name);
console.log("req.codedescription"+req.body.codedescription);
};
Submit form without enctype="multipart/form-data" is working but I can not get files.
Submit form with enctype="multipart/form-data" is working but I can not get files as well as data.
you can try this
<html>
<head>
<title>FileUpload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "http://localhost:3000/api/photo"
method = "post"
>
<input type="file" name="userPhoto" multiple />
<input type="submit" value="Upload Image" name="submit" id="btnUpload">
<span id="spnStatus" />
</form>
<script>
$(document).ready(function(){
$('#btnUpload').click(function(){
$('#spnStatus').empty().text("File is Uploading");
$(this).ajaxSubmit({
error : function(xhr){
status('Error : '+xhr.status);
}
success : function(response){
$('#spnStatus').empty().text(xhr);
}
});
});
});
</script>
</body>
</html>
NodeJS Express
var express = require("../node_modules/express");
var multer = require('../node_modules/multer');
var bodyParser = require("../node_modules/body-parser");
var app = express();
app.use(bodyParser.json());
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage }).array('userPhoto',8);
app.get('/',function(req,res){
res.sendFile(__dirname + "/fileUpload.html");
});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
if(err) {
console.log(err);
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3001,function(){
console.log("Working on port 3001");
});
Now you can upload upto 8 files at a time, if you want to upload more than eight, just edit var upload = multer({ storage : storage }).array('userPhoto','LIMITHERE');
#karthik comment, i think you need this as well including after jquery, when you want to use his example:
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
Related
I am working on an Image Upload server using multer and mongodb following This GeeksForGeeks Post:
https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/
I did everything same as in this post but my localhost server is just loading and loading.
My Project Structure :
https://i.stack.imgur.com/p1NhC.png
App.js:
// Step 1 - set up express & mongoose
var express = require('express')
var app = express()
var bodyParser = require('body-parser');
var mongoose = require('mongoose')
var fs = require('fs');
var path = require('path');
require('dotenv/config');
// Step 2 - connect to the database
mongoose.connect(process.env.MONGO_URL,
{ useNewUrlParser: true, useUnifiedTopology: true }, err => {
console.log('connected')
});
// Step 3 - code was added to ./models.js
// Step 4 - set up EJS
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// Set EJS as templating engine
app.set("view engine", "ejs");
// Step 5 - set up multer for storing uploaded files
var multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({ storage: storage });
// Step 6 - load the mongoose model for Image
var imgModel = require('./model');
// Step 7 - the GET request handler that provides the HTML UI
app.get('/', (req, res) => {
imgModel.find({}, (err, items) => {
if (err) {
console.log(err);
res.status(500).send('An error occurred', err);
}
else {
res.render('imagesPage', { items: items });
}
});
});
// Step 8 - the POST handler for processing the uploaded file
app.post('/', upload.single('image'), (req, res, next) => {
var obj = {
name: req.body.name,
desc: req.body.desc,
img: {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
contentType: 'image/png'
}
}
imgModel.create(obj, (err, item) => {
if (err) {
console.log(err);
}
else {
// item.save();
res.redirect('/');
}
});
});
// Step 9 - configure the server's port
var port = process.env.PORT || '3000'
app.listen(port, err => {
if (err)
throw err
console.log('Server listening on port', port)
})
Model.js:
// Step 3 - this is the code for ./models.js
var mongoose = require('mongoose');
var imageSchema = new mongoose.Schema({
name: String,
desc: String,
img:
{
data: Buffer,
contentType: String
}
});
//Image is a model which has a schema imageSchema
module.exports = new mongoose.model('Image', imageSchema);
.env:
MONGO_URL = mongodb://localhost/mongo
PORT = 5500
imagesPage.ejs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Uploading</title>
</head>
<body>
<h1>To Upload Image on mongoDB</h1>
<hr>
<div>
<form action="/" method="POST" enctype="multipart/form-data">
<div>
<label for="name">Image Title</label>
<input type="text" id="name" placeholder="Name"
value="" name="name" required>
</div>
<div>
<label for="desc">Image Description</label>
<textarea id="desc" name="desc" value="" rows="2"
placeholder="Description" required>
</textarea>
</div>
<div>
<label for="image">Upload Image</label>
<input type="file" id="image"
name="image" value="" required>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
<hr>
<h1>Uploaded Images</h1>
<div>
<% items.forEach(function(image) { %>
<div>
<div>
<img src="data:image/<%=image.img.contentType%>;base64,
<%=image.img.data.toString('base64')%>">
<div>
<h5><%= image.name %></h5>
<p><%= image.desc %></p>
</div>
</div>
</div>
<% }) %>
</div>
</body>
</html>
Please tell what i am doing wrong.
I very new to backend so I don't know what to do
Thanks
I am uploading a file using multer but the problem is as I am trying to check if it's being uploaded or not using if (req.body.file) the app will not crash but the browser will say that the page is not available. Is there another way of checking if the file will be uploaded?
var multer = require('multer');
var storage = multer.diskStorage({
//multers disk storage settings
destination: function (req, file, cb) {
cb(null, 'public/uploads/')
},
filename: function (req, file, cb) {
//var datetimestamp = Date.now();
cb(null, file.originalname)
}
});
var upload = multer({
storage: storage
})
router.post('/adduser', upload.single('image'), function (req, res) {
console.log(req.body.name);
var data = {
name: req.body.name,
password: req.body.password,
image: 'uploads/' + req.file.originalname
}
users.insert(data, function (err, data) {
console.log(data);
res.redirect('/home');
});
});
<form action="/adduser" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="password" name="password" />
<input type="file" name="image" />
<input type="submit">
</form>
I am trying to upload a file to disk using multer. Here is my code:
const multer = require('multer');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + '/uploads/')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname)
}
});
var upload = multer({storage: storage});
And here goes my form to collect the file and some extra input fields
<form method="post" enctype="multipart/form-data" action="/uploadfile">
<input name="cate" type="hidden" value="<%= category %>" id="cate" name="cate"></input>
<br>
<input type="file" name="uploadfile" class="btn-success" value="Select Source">
<input type="submit" class="btn-success" ><i class="fas fa-plus"></i> Add a new Source</input>
This function uploads public/img/bg.jpg to my database, thou i would like the file to be picked by the user. How can i get the filepath string in req.files object
fs.createReadStream('public/img/bg.jpg')
.pipe(fileUpload.createWriteStream())
.on('error', function(err) {
console.log("fail");})
.on('finish', function() {
console.log("success");
});
});
I have a file upload in node js. I want to show a line displaying upload started / upload failed / upload completed and a graphic progress bar.
How can I implement this?
Node.js:
var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './upload');
},
filename: function (req, file, cb) {
cb(null, file.originalname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).array('file', 3);
router.get('/', function(req, res){
res.send( {success: 'File uploaded!'});
})
router.post('/upload', function(req,res){
upload(req,res,function(err) {
console.log('Selected Files: ', req.files);
if(err){
res.end("Error: '" , err , "'");
}else{
console.log('Files uploaded!');
res.sendStatus(204);
}
});
});
module.exports = router;
HTML
<form enctype = "multipart/form-data"
action = "/upload"
method = "POST"
>
<input type="file" name="file"/>
<p></p>
<input type="file" name="file"/>
<p></p>
<input type="submit" value="Upload File" name="submit">
</form>
<p id="success">{{success}}</p>
Use XMLHttpRequest and .addEventListener("progress") on the client side to submit the form
I am new in node. I just want to pass value in POST request with something like uploading of file. here is my sample code:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var multer = require('multer');
var upload = multer({ dest: '/tmp/'});
app.use(express.static('public'));
app.post('/process_post', urlencodedParser, function (req, res) {
console.log(req.files.file.name);
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:'Save successfully',
first_name:req.body.firstname,
last_name:req.body.lastname,
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
HTML:
<html>
<body>
<form action="http://127.0.0.1:8081/process_post" method="POST" enctype="multipart/form-data">
First Name: <input type="text" name="firstname">
<br>
Last Name: <input type="text" name="lastname">
<br>
Picture: <input type="file" name="file" size="50" />
<br>
<input type="submit" value="Submit">
</form>
</body></html>
The req.files is always undefine.
Thanks in advance!
You're requireing multer, but never configuring or using it. from the docs:
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
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
})