I have used following code :
fileupload.html
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://127.0.0.1:8081/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
fileupload.js:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
//console.log(multer);
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}));
app.get('/fileupload.html', function (req, res) {
res.sendFile( __dirname + "/" + "fileupload.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)
})
I have used these above code for file uploading But when excute using node fileupload.js in terminal i am getting type error TypeError('app.use() requires middleware functions');
Can any one help to resolved this problem.
Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.
Use this code, hope this will help you.
It seems that it's not safe to keep original file name or extension and I found/made this code for displaying images directly everywhere by adding .jpg to your file url:
You're trying to use
multer
's old API. It changed awhile back, see the documentation for more information.In your particular case of uploading a single file, you would remove the
app.use(multer({ ... }))
line and instead use.single()
andreq.file
like:The above solution doesn't worked for me so I have used storage method:
it works for me correctly