Multer Unexpected field - javascript

I'm trying to upload a file into my project using multer, but I have no idea how to do it.
here's some of the code I wrote thinking it could work
// here's my ejs view
<form action="/wistia" method="post" enctype="multipart/form-data">
<input type="file" name="archivo">
<input type="submit">
</form>
// here's my route file
const multer = require("multer");
const express = require('express');
const router = express.Router();
let location = path.join(__dirname, '/uploads');
let upload = multer({ dest: location });
router.get("/wistia",function(req, res){
res.render("wistia");
});
router.post("/wistia", upload.single("archivo") , function(req, res) {
console.log(req.file);
});
thanks.

Try making this change
var upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null,location);
}
})
});

Related

Multer doesn't save the file to the web server

Hey I'm trying to use multer to save files on the web server but it doesn't work.
I tried every answer on stack overflow but nothing solves it. No error it just doesn't work. I tried running it both locally and on Openshift.
Here's the relevant lines from my code.
Client side:
<form id="upload_form" method="POST" action="/submit_upload" enctype="multipart/form-data">
<input type="text" id="name" name="name"><br>
<input type="file" id="software" name="software"><br>
<input type="submit" value="Upload">
</form>
Server side:
const express = require("express");
const multer = require("multer");
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended = true }));
var storage = multer.diskStorage({
destination: "uploads/",
filename: function(req, file, cb) {
cb(null, file.fieldname);
}
});
var upload = multer({ storage: storage, limits: { fieldSize: 10 * 1024 * 1024 } }).single("software");
app.post("/submit_upload", upload, function(req, res) {
console.log(req.body); // is alright
console.log(req.file); // undefined
}
app.listen(8080, function() { console.log("started"); });

Req.file undefined with express-fileupload and multer packages

I tried all possible scenarios and I tried with multiple variations and approaches suggested by documentation and by other stackoverflow questions.
Any of them worked -> I keep getting req.file is: undefined
Form:
<form action="/send" enctype="multipart/form-data" method="POST">
<input type="file" id="file" name="file">
<button type="submit">Submit</button>
Express Setup:
const express = require('express');
const ejs = require('ejs');
const homeController = require('./controlers/homeController');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.listen(3000);
/* routes */
app.use(homeController);
I have the following code:
var multer = require('multer')
const storage = multer.diskStorage({
destination: './public/data/uploads',
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
var upload = multer({
storage: storage
}).single('file');
router.get('/', (req, res) => {
res.render('home')
})
router.post('/send', (req, res) => {
upload(req, res, (err) => {
if (err) console.log(err);
console.log('req.file is: ' + req.file);
});
})
I spent 2 days trying to figure this out but I can't see the light at the end of the tunnel, and i just want to get the file from client and send it with nodemailer as attachement later on.
Answer obtained based on eMAD suggestion on question How to perform an HTTP file upload using express on Cloud Functions for Firebase (multer, busboy)
Solution below:
File is saved on the storage location you define in muller.
req.files is an array with the details of the file/files you upload.
PS: thanks #eol for pointing me in this direction
const contactControler = require('../controlers/contactController');
const busboy = require('busboy')
const express = require('express');
const router = express.Router();
var multer = require('multer');
const SIZE_LIMIT = 10 * 1024 * 1024 // 10MB
var stor = multer.diskStorage({
destination: '../public/cv',
filename: function(req, file, callback) {
callback(null, file.originalname);
}
});
const multipartFormDataParser = multer({
storage: stor,
// increase size limit if needed
limits: { fieldSize: SIZE_LIMIT },
// support firebase cloud functions
// the multipart form-data request object is pre-processed by the cloud functions
// currently the `multer` library doesn't natively support this behaviour
// as such, a custom fork is maintained to enable this by adding `startProcessing`
// https://github.com/emadalam/multer
startProcessing(req, busboy) {
req.rawBody ? busboy.end(req.rawBody) : req.pipe(busboy)
},
})
router.post('/send', multipartFormDataParser.any(), contactControler.send);
Please try adding upload in your route as middleware.
router.post('/send', upload, (req, res) => { ...

Upload file to aws S3 bucket using absolute path

I am trying to upload files from Express ejs to AWS s3 bucket I am successful in doing so but when I am trying to select files from other directory or folder other than where my index.js is it doesn't accept the file and throw error file not found.
index.js
'use strict';
const express = require('express');
const app = express();
const multer = require('multer');
const multerS3 = require('multer-s3');
const AWS = require('aws-sdk');
const bodyParser = require('body-parser');
const s3 = new AWS.S3({
accessKeyId: '',
secretAccessKey: ''
});
app.use(bodyParser.urlencoded({extended : true}));
app.set('view engine', 'ejs');
const uploadS3 = multer({
storage: multerS3({
s3: s3,
bucket: '',
metadata: (req, file, cb) => {
cb(null, {fieldName: file.fieldname})
},
key: (req, file, cb) => {
cb(null, Date.now().toString() + '-' + file.originalname)
}
})
});
test.ejs
<html>
<form method="post" action="/upload">
<input type="file" name="file" />
<input type="submit" />
</form>
</html>
route.js
var fileupload = require('../../common/service/file-upload');
//some code in between
app.post('/upload', fileupload.uploadS3.single('file'),(req, res) => {
console.log(req.file);
});
whenever you are uploading the files you need to add attribute to form enctype="multipart/form-data". .then it will work.
to upload files to s3 use multer-s3 package which is simple to configure
Refrence : https://www.npmjs.com/package/multer-s3
so your test.ejs file will be like this
<html>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
<const/form>
</html>
and index.js
const express = require('express');
const bodyParser = require('body-parser');
const AWS = require('aws-sdk');
const multer = require('multer')
const multerS3 = require('multer-s3')
const app = express();
const s3 = new AWS.S3({
accessKeyId: //aws access key ,
secretAccessKey: //aws secret key
});
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'some-bucket',
metadata: function (req, file, cb) {
cb(null, {fieldName: file.fieldname});
},
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
})
app.post('/', upload.single('file'), (req, res) => {
res.json({
message: "File uploaded to S3"
});
});
Man, how could Express read client's file by path? The files are uploaded / sent in the POST request.
Use some body parser that support multipart/form-data file upload, like mutler, to parse the file from the request & upload it to S3.
In example...
html
<html>
<!-- don't forget enctype parameter -->
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
</html>
node server using AWS and multer manually
const multer = require('multer'),
AWS = require('aws-sdk'),
S3 = new AWS.S3({
...
});
router.post('/', multer().single('file'), (req, res) => {
// debug req.file
console.log(req.file);
S3.upload({
Bucket: '...',
Key: req.file.originalname,
Body: req.file.buffer
}, (err, res) => {
if (err) throw err;
res.json({
message: "File uploaded to S3"
});
});
});
node server using multer-s3
const multer = require('multer'),
multerS3 = require('multer-s3'),
AWS = require('aws-sdk'),
S3 = new AWS.S3({
...
});
let upload = multer({
storage: multerS3({
s3: s3,
bucket: '...',
key: (req, file, cb)
=> cb(null, file.originalname), // or whatever Key you like
})
});
router.post('/', upload.single('file'), (req, res) => {
res.json({
message: "File uploaded to S3"
});
});

Express 4 use multer as middleware got error

var express = require('express');
var router = express.Router(),
multer = require('multer');
var uploading = multer({
dest: __dirname + '../public/uploads/',
})
router.post('/upload', uploading, function(req, res) {
console.log('uploaded');
})
I got an error Route.post() requires callback functions error following a photo upload tutorial here. Maybe it's cause by the newer version of expresss? I remember above is the way how we put middle in a route, but why here it doesn't work?
Basing on the multer docs, it seems like you have to use uploading.single() or uploading.array() as your middleware. This example is obtained from the example usage in the multer docs:
var upload = multer({ dest: 'uploads/' })
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
})
var express = require('express');
var router = express.Router(),
multer = require('multer');
var uploading = multer({
dest: __dirname + '../public/uploads/',
})
var type = uploading.single('file');
router.post('/upload', type, function(req, res) {
console.log('uploaded');
})

Uploading files with multer (nodeJs) doesn't work

I'm trying to upload multiples files with a modal that contains a form with an input.
My modal (jade template format) :
#modalAddFile.modal
form#uploadForm(enctype='multipart/form-data', action='/#{category}/addFiles', method='post')
.modal-content
.file-field.input-field
.btn
span Ajouter
input(type='file', name='songs', multiple)
.file-path-wrapper
input.file-path.validate(type='text')
.modal-footer
a#cancel.modal-action.modal-close.waves-effect.waves-red.btn-flat(href='#!') Annuler
button#addFile.modal-action.modal-close.waves-effect.waves-green.btn-flat(type='submit', name='action', href='#!') Valider
routes.js :
var express = require('express');
var router = express.Router();
//Upload file
var multer = require('multer');
var upload = multer({ dest: '../public/test/' });
//Add files
router.post('/:category/addFiles', upload.array('songs'), function (req, res, next) {
res.redirect('/');
});
module.exports = router;
I don't have any apparent error (200 success), I don't know what is wrong.
Try to use this code:
var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../public/test/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname)
}
});
var upload = multer({ storage: storage });
//Add files
router.post('/:category/addFiles', upload.any(), function (req, res, next) {
res.redirect('/');
});
module.exports = router;

Categories

Resources