Multer returning req.file undefined - javascript

I know this question has been asked plenty of times before, and I've tried implementing those solutions, but they don't really work for me.
I have been tearing my hair out trying to figure out how to upload a file and read the file size through Node. I initially tried using the formidable npm, which seems to no longer be maintained as I can't find documentation on it. I had no way of dealing with the errors so I tried using multer. However, I repeatedly get an undefined log when I try to log req.file.
I have the server.js code below
var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');
var app = express();
var PORT = 8080;
app.use(express.static(__dirname+'/views'));
app.set('views', './views');
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index.jade');
});
app.post('/upload', upload.single('Upload'),function(req, res){
console.log(req.file);
});
app.listen(PORT, function(){
console.log('Express listening on port: '+PORT);
});
My javascript code with the AJAX call is provided below
$('#upload-butt').on('change', function(){
var file = $(this).get(0).files;
console.log(typeof file);
if(file.length > 0){
var formData = new FormData();
formData.append('Upload', file, file.name);
$.ajax({
url: '/upload',
type: 'POST',
data:formData,
processData:false,
contentType:false,
error: function(jXhr, status){
console.log('error: '+status);
},
success: function(data){
console.log('upload successful: '+data);
}
})
}
});
My index.jade code is given below
html
head
link(rel='stylesheet', href='style.css', type='text/css')
title Upload file for shortening
body
h1 Welcome to file metadata service
div(id='upload-button')
form(enctype='multipart/form-data', method='post', action='/upload')
input(name='Upload', type='file', id='upload-butt')
div(id="submit-button")
form(action = '/submit')
button(type="submit", value='Submit', id='submit-butt') Submit
script(src="https://code.jquery.com/jquery-2.2.0.min.js")
script(src="upload.js")
I am ready to tear my hair out, so I will be very grateful to anyone who can help me here! Thanks!

You have not applied middle correctly.
You can use something like this:
var express = require('express')
var multer = require('multer')
var app = express()
app.use(multer({ dest: './uploads/'}))
You can access the fields and files in the request object:
console.log(req.body)
console.log(req.files)
So similarly in ur code you have to apply
var express = require('express');
var formidable = require('formidable');
var multer = require('multer');
var path = require('path');
var upload = multer({dest: './uploads'});
var fs = require('fs');
var app = express();
var PORT = 8080;
app.use(upload);
app.use(express.static(__dirname+'/views'));
app.set('views', './views');
app.set('view engine', 'jade');
app.get('/', function(req, res){
res.render('index.jade');
});
app.post('/upload', upload.single('Upload'),function(req, res){
console.log(req.file);
});
app.listen(PORT, function(){
console.log('Express listening on port: '+PORT);
});

You're submitting a different <form> than the one with the image, the correct way is to place all content in a single <form>. This way you're submitting the form which includes the file.
html
head
link(rel='stylesheet', href='style.css', type='text/css')
title Upload file for shortening
body
h1 Welcome to file metadata service
div(id='upload-button')
form(enctype='multipart/form-data', method='post', action='/upload')
input(name='Upload', type='file', id='upload-butt')
button(type="submit", value='Submit', id='submit-butt') Submit
script(src="https://code.jquery.com/jquery-2.2.0.min.js")
script(src="upload.js")
This should work, for the jade part.
(docs about multer)

Related

Updating Json file in node but fiving previously saved results

I have a simple node script in which I update the db.json file through the form. It updates the file but when I render it in response for a get or post out it gives previous results only.
var cors = require('cors')
const express = require('express');
const app = express();
var jsonfile = require('jsonfile');
var file = './db.json'
var filex = require('./db.json')
app.engine('html', require('ejs').renderFile);
app.use(cors())
const http = require('http');
const port = process.env.PORT || 3000
const bp = require('body-parser')
app.use(bp.json())
app.use(bp.urlencoded({ extended: true }))
app.set('view engine', 'html')
// Defining get request at '/' route
app.get('/', function(req, res) {
res.send("<html><head><title>Json</title></head><body><form id='form1' action='/gettingdata' method='post'><input type='text' name='usrid' /><button type='submit' form='form1' value='Submit'>Submit</button></form></body></html>")
});
app.post('/gettingdata',function(req,res){
var user_id = req.body.usrid;
var obj = JSON.parse(user_id)
jsonfile.writeFileSync(file, obj,{flag: 'w'});
res.send('updated');
})
app.post('/api',function(req,res){
res.send(filex)
})
app.get('/api',function(req,res){
res.send(filex)
})
//extra
app.post('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.get('/api/v1/users/initial_authentication',function(req,res){
res.send(filex)
})
app.listen(port, function(req, res) {
console.log("Server is running at port 3000");
});
It only gives updated results on redeveloping of server.
var filex = require('./db.json')
So, filex only load the file when the server starts. If you try to get the most updated content of file db.json, please re-load the file.
I guess res.send(require('./db.json')) may work as expected.
I have solved this issue using
delete require.cache[require.resolve('./db.json')]

multer upload returns 500 with python post

I am trying to upload a single image using python code to a node js express server. The python code is:
import requests
url = 'http://localhost:9000/testAPI/uploadphoto'
files = {'file': ('photo', open('test.jpg', 'rb'))}
ret = requests.post(url, files=files)
print ret
For the app.js, it is mostly following the default template:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser= require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require("./routes/testAPI");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({extended: true}))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
and I am using the router testAPI for handling the POST:
var express = require('express');
var multer = require('multer');
var router = express.Router();
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads')
},
filename: function (req, file, cb) {
var filename = file.originalname;
var fileExtension = filename.split(".")[1];
cb(null, Date.now() + "_" + filename);
}
});
var upload = multer({ storage: storage });
router.get('/', function(req, res, next) {
console.log("test");
res.send('API is working properly');
});
router.post('/uploadphoto', upload.single('photo', (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send('Photo uploaded');
}));
module.exports = router;
When I run the python code, the server returns 500. In my node js directory, I have an uploads folder created.
At the first you should run your node server project in port 9000
Your npm start probably calls your bin/www file. Which contains the listen invocation to start your app.
Many people set up their app this way. eg. app.js to define and configure their app, and something like bin/www to actual get the server running. This way they can include the app.js into other parts, say tests, without actually starting the server when you require it.
Figured it out. Since my server is started in the bin/www file as opposed to the app.js file, from the terminal I went into my bin directory and then called
node wwww
or
nodemon www
or add this code to the app.js and then run it with node app.js to listen port 9000
const port = 9000;
app.listen(port, () => console.log(Example app listening on port ${port}!))

Failure to upload files on Glitch using Express js

I created a Glitch project and I want to upload files to it via user input. I am using express-fileupload and I followed the sample code from their docs to upload a file, but I keep getting an error. I think it might have to do with the directory I am using to move the file to. I have tried using '/app/views/uploads' and 'uploads/' as well as '/assets' (I used assets.js to do so) and I haven't been able to store the file. Here's my code:
var express = require('express');
var fileUpload= require('express-fileupload');
var app = express();
var assets = require("./assets");
app.use("/assets", assets);
app.use(express.static('views'));
app.use(fileUpload());
app.set('view engine', 'ejs');
app.set('views', 'views');
app.get("/", function (request, response) {
response.render('index');
});
app.get('/fileupload', function(req, res) {
res.render('upload');
});
app.post('/upload', function(req, res) {
var sample= req.files.sample;
sample.mv('/assets', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
var listener = app.listen(process.env.PORT, function () {
console.log('SERVER STARTED ON PORT ' + listener.address().port);
});
The file is received succesfully, so the file not being there is not why I get errors.
I normally get this as the error:
{"errno":-13,"code":"EACCES","syscall":"open","path":"/assets"}
If you know where to upload the files to, please let me know. Any help would be very appreciated!

Conflict with express.js - Cannot get my static files

Hello, I'm using express.js to make a webapp to buy tickets. So I have a page that direct a person to a info about the party, however, when I try load the static files to this page, the express.js cannot get.
On console view I saw that a new directory, with name of the path for the url, is setting before of static folder.
My app.js file:
var express = require('express');
var path = require('path');
var teste = require('./db/teste.json')
var app = express();
var list = Object.keys(teste).map( (value) => teste[value]);
app.set('view engine', 'jade');
app.set('views', (__dirname + '/views'));
app.use('/static', express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index')
});
app.get('/login/', function(req, res){
res.render('login')
});
app.get('/dash/:title?', function(req, res){
var title = req.params.title;
if(title === undefined){
res.status(503);
var isDash = true;
res.render('dash', {db: list, isDash: isDash});
}else{
var festa = teste.title;
res.render('party', {db: festa, isDash: isDash});
}
});
The console view:
PS: Only happens in this page.
Thank you!
Because the page is localhost:3000/dash/name-of-party, static resources that use relative URL will be referenced relative to that page, so, e.g.:
<img src="static/something.jpg">
Will be retrieved with a full url of: http://localhost:3000/dash/static/something.jpg. Instead you could use src="/static/something.jpg" (notice the leading slash) and it may work. Just to confirm this is the issue you could add:
app.use('/dash/static', express.static(path.join(__dirname, 'public')));
Right after the existing line that maps static resources.

serving html files in node js using express

actally i'm trying to serve a html file in the browser using node js and express. unfortunatly i can't get the correct appearence of the html file.
here is the code :
var http = require('http');
var fs = require('fs');
// Chargement du fichier index.html affiché au client
var server = http.createServer(function(req, res) {
fs.readFile('./table.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
To send a single file for a specific route use the res.sendFile() function.
var express = require('express');
var app = express();
var path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.resolve('path/to/my/file.html'));
});
app.listen(3000);
In case you want to serve all files in a directory use the express.static() middleware
var express = require('express');
var app = express();
app.use(express.static('path/to/my/directory'));
app.listen(3000);
With express u can do something like
//init the app to extend express
var express=require("express");
var app=express();
//inside the http callback
var server = http.createServer(function(req, res) {
app.use(express.static("./file"));
})
server.listen(8000);

Categories

Resources