我在Nodejs编码方面很天真,无法进一步解决问题,这是文件上传程序: 这是我的代码:
var express=require('express');
var app=express();
var fs=require("fs");
var bodyParser=require('body-parser');
var multer=require('multer');
var jsonParser=bodyParser.json();
app.use(express.static('public'))
app.use(bodyParser.urlencoded({extended:false}));
var upload=multer({dest:'/tmp/'});
app.get('/index.htm',function(req,res){
res.sendFile(__dirname+"/"+"index.htm");
})
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 Upload 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)
})
然而,应用程序正在运行,但它显示'无法POST / file_upload,请告诉我该怎么做?
答案 0 :(得分:0)
试试这个
app.post('/file_upload', function (req, res) {
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, '/tmp/');
},
filename: function (req, file, callback) {
callback(null, Date.now()+path.extname(file.originalname));
}
});
var upload = multer({storage: storage}).single('file');
upload(req, res, function (err) {
if (err) {
console.log(err);
}
else {
res.status(200);
res.json({
message:'File Upload Successfully'
});
}
});
}