一输莺、目標(biāo)
- 完成單文件上傳毅往,并進(jìn)行復(fù)制到其他目錄
- 完成上傳文件的列表的顯示功能
- 使用Vue+Ajax完成圖片的前端頁(yè)面展示
二、參照
可以參照前面兩篇文章芬为,本是對(duì)功能的進(jìn)一步增強(qiáng)
三萄金、服務(wù)器
- 文件結(jié)構(gòu):
/
app.js
-public/
index.html
+images/
+uploads/
+node_modules/
package.json
- package.json的依賴部分
"dependencies": {
"express": "^4.17.1",
"multer": "^1.4.2"
}
- app.js的內(nèi)容
//app.js
const fs=require('fs')
const express=require('express')
const http=require('http')
//文件上傳中間件(指定上傳的臨時(shí)文件夾是/uploads)
const multer=require('multer')
let upload = multer({ dest: 'uploads/' })
let app=express();
const FILE_PATH="public/images/"
//HttpServer服務(wù)的中間件(public目錄下的index.html為首頁(yè))
app.use(express.static('public'))
//文件上傳的處理(avatar是上傳時(shí)的filedName)
app.post('/upload', upload.single('avatar'), function (req, res, next) {
//req.body是普通表單域
//req.file是文件域
let msg={
body:req.body,
file:req.file
}
//將臨時(shí)文件上傳到/public/images中
let output=fs.createWriteStream(FILE_PATH+req.file.originalname)
let input=fs.createReadStream(req.file.path)
input.pipe(output)
res.json(msg)
})
//接收前端的請(qǐng)求蟀悦,返回上傳圖片的列表
app.get("/files",function (req,res) {
fs.readdir('public/images',function (err,dir) {
res.json(dir)
})
})
//啟動(dòng)Express服務(wù)器
let server=http.createServer(app);
server.listen(8000,function () {
console.log("start server at port 8000")
})
- /public/index.html的內(nèi)容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<style type="text/css">
li{
list-style: none;
display: inline-block;
}
li img{
margin: 10px;
}
</style>
</head>
<body>
<h1>您上傳的照片墻</h1>
<div id="app">
<ul>
<li v-for="img of images">
<img :src="'images/'+img" alt="" width="300px">
</li>
</ul>
</div>
<script>
new Vue({
el:'#app',
data:{
images:[]
},
created(){
fetch("/files",{method:'GET'})
.then(res=>res.json())
.then(files=>{
this.images.push(...files)
})
}
})
</script>
</body>
</html>