How To Upload Image File And Display Using Express Nodejs
File Upload:
SSolution 1:
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()
and req.file
like:
var upload = multer({ dest: '/tmp/'});
// File input field name is simply 'file'
app.post('/file_upload', upload.single('file'), function(req, res) {
var file = __dirname + '/' + req.file.filename;
fs.rename(req.file.path, file, function(err) {
if (err) {
console.log(err);
res.send(500);
} else {
res.json({
message: 'File uploaded successfully',
filename: req.file.filename
});
}
});
});
Solution 2:
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.
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({ dest: '/tmp' })
app.get('/fileupload.html', function (req, res) {
res.sendFile( __dirname + "/" + "fileupload.html" );
})
app.post('/file_upload', upload.single("file"), function (req, res) {
var file = __dirname + "/" + req.file.originalname;
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.error( err );
response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
}else{
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().addressvar port = server.address().portconsole.log("Example app listening at http://%s:%s", host, port)
})
Solution 3:
The above solution doesn't worked for me so I have used storage method:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var ext = require('path').extname(file.originalname);
ext = ext.length>1 ? ext : "." + require('mime').extension(file.mimetype);
require('crypto').pseudoRandomBytes(16, function (err, raw) {
cb(null, (err ? undefined : raw.toString('hex') ) + ext);
});
}
});
var upload = multer({ storage: storage });
app.post('/file_upload', upload.any(), function (req, res, next) {
res.send(req.files);
})
Solution 4:
it works for me correctly
var express = require('express'),
http = require('http'),
formidable = require('formidable'),
fs = require('fs'),
path = require('path');
var bodyParser = require('body-parser');
var multer = require('multer');
var upload = multer({ dest: '/tmp/'});
var app = express();
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
var server = app.listen(3000, function() {
console.log('leistening on port', server.address().port);
})
app.post('/upload', upload.single('file'), function(req, res) {
var file = 'uploads' + '/' + req.file.originalname;
fs.rename(req.file.path, file, function(err) {
if (err) {
res.send(500);
} else {
res.json({
message: 'File uploaded successfully',
filename: req.originalname
});
}
});
});
<!DOCTYPE html><!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--><!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--><!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--><!--[if gt IE 8]><!--><htmlclass="no-js"><!--<![endif]--><head><metacharset="utf-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><title></title><metaname="description"content=""><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel="stylesheet"href=""></head><body><formaction="http://127.0.0.1:3000/upload"enctype="multipart/form-data"method="post"><inputtype="text"name="title"><inputtype="file"name="file"><inputtype="submit"value="Upload"></form></body></html>
Solution 5:
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:
restapi.get('/uploads/:id', function (req, res) {
var storedMimeType = 'image/jpeg';
res.setHeader('Content-Type', storedMimeType)
fs.createReadStream(path.join('./uploads/', req.params.id).replace(/\.[^/.]+$/, "")).pipe(res)
})
Post a Comment for "How To Upload Image File And Display Using Express Nodejs"