我试着按照一些教程上传文件在节点js ..但它似乎上传图像是不工作。它显示
错误:错误:没有这样的文件或目录,请打开"C:\用户\用户\下载\文件上传\pexels-luiisrtz-1693399.jpg"
我试着找出代码中的错误,但似乎我做的是正确的。会不会是代码过时了?
这是我的app.js代码
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var path = require('path');
var picSchema= new mongoose.Schema({
picpath:String
})
var picModel = mongoose.model('picsdemo',picSchema);
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'./public/uploads')
},
filename:function(req,file,cb){
cb(null,file.originalname)
}
})
var upload = multer({storage:storage})
var app = express();
mongoose.connect('mongodb://localhost:27017/pics',{useNewUrlParser:true})
.then(()=>console.log('connected')).catch(err=>console.log('error ocured',err));
app.set('views',path.resolve(__dirname,'views'));
app.set('view engine','ejs');
var pathh = path.resolve(__dirname,'public');
app.use(express.static(pathh));
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',(req,res)=>{
picModel.find((err,data)=>{
if(err){
console.log(err)
}
else if(data.length>0){
res.render('home',{data:data})
}
else{
res.render('home',{data:{}})
}
})
})
app.post('/',upload.single('pic'),(req,res)=>{
var x = 'uploads/'+req.file.originalname;
var temp = new picModel({
picpath:x
})
temp.save((err,data)=>{
if(err){
console.log(err)
}
res.redirect('/')
})
})
app.get('/download/:id',(req,res)=>{
picModel.find({_id:req.params.id},(err,data)=>{
if(err){
console.log(err)
}
else{
var x= __dirname+'/public/'+data[0].picpath;
res.download(x)
}
})
})
var port = process.env.PORT || 3000 ;
app.listen(port,()=>console.log('server running at port'+port))
这个home.ejs代码的网站布局
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="/" method="POST" enctype="multipart/form-data">
<input type="file" name="pic" id="pic"><br>
<input type="submit" value="upload file">
</form><br><br><br><br>
<% if(data.length > 0) {%>
<table>
<thead>
<tr>
<td>
images
</td>
<td>
download
</td>
</tr>
</thead>
<tbody>
<% for(var i=0; i< data.length; i++) {%>
<tr>
<td>
<img src="<%= data[i].picpath%>" alt="images" style="width:100px; height:100px;">
</td>
<td>
<form action="/download/<%= data[i]._id%>">
<input type="submit" value="download">
</form>
</td>
</tr>
<% } %>
</tbody>
</table>
<% } %>
</body>
</html>
在这段代码中我使用了这个依赖关系
"主体解析器":"^1.19.0","ejs":"^2.7.1","表达":"^4.17.1"," Mongoose ":"^5.7.7","多个":"^1.4.2"
2条答案
按热度按时间von4xj4u1#
Multer将尝试将上传的图像放到
public/uploads
文件夹中,但该文件夹可能不存在。尝试在其中创建
public
文件夹和uploads
文件夹,然后重试。biswetbf2#
您还可以使用fsGrid将图像上载到数据库