Working on sometime I got a solution using multer module.Using this module you can upload both files and images.And it successfully uploaded to the destination folder.
Here is my server code app.js
var express =r equire('express');
var multer = require('multer');
var path = require('path')
var app = express();
var ejs = require('ejs')
app.set('view engine', 'ejs')
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, './public/uploads')//here you can place your destination path
},
filename: function(req, file, callback) {
callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
app.get('/api/file',function(req,res){
res.render('index');
});
app.post('/api/file', function(req, res) {
var upload = multer({
storage: storage}).single('userFile');
upload(req, res, function(err) {
console.log("File uploaded");
res.end('File is uploaded')
})
})
app.listen(3000,function(){
console.log("working on port 3000");
});
Create a views
folder and place this index.ejs
file in it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data" method="post">
<input type="file" name="userFile" />
<input type="submit" value="Upload File" name="submit">
</form>
</body>
</html>
After this run the server as node app.js
.Open the browser and type http://localhost:3000/api/file
after runnig this url choose a file which you want to upload to destination folder.And have a successfull response in both terminal and browser.Hope this helps for you.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…