今天寫瀑布流的時候峰搪,想自己用node創(chuàng)建后臺服務橄镜。就寫了圖片上傳的demo。自己在過程中學到很多顷链。
vue文件代碼:
<template>
??<div>
????菜單管理
????<el-upload
??????class="upload-demo"
??????action
??????:auto-upload="false"
??????:on-remove="handleRemove"
??????:before-remove="beforeRemove"
??????multiple
??????:on-change="onChange"
????>
???<el-button?icon="el-icon-upload"?type="primary"?style="margin-top:?20px;"? >選擇</el-button??????>
????</el-upload>
????<el-button
??????icon="el-icon-upload"
??????type="primary"
??????style="margin-top:?20px;"
??????@click="submitUpload"
??????>上傳</el-button
????>
??</div>
</template>
<script>
import?axios?from?'axios'
export?default?{
??data?()?{
????return?{
??????fileList:?[]
????}
??},
??methods:?{
????submitUpload?()?{
??????let?formData?=?new?FormData()
??????this.fileList.forEach(file?=>?{
????????formData.append('file',?file)
??????})
??????axios.post('http://localhost:4000/saveImage',?formData).then(res?=>?{})
????},
????handleRemove?(file,?fileList)?{},
????beforeRemove?(file,?fileList)?{},
????onChange?(file,?fileList)?{
??????if?(file)?{
????????this.fileList.push(file.raw)
??????}
????}
??}
}
</script>
<style></style>
nodejs代碼:
所有的require模塊都需要 npm install 模塊 -s
const?cors?=?require('koa2-cors')? //解決跨域 本文是http://localhost:8080 向http://localhost:4000 跨域請求
var?fsr?=?require('fs-extra') //把圖片從臨時文件夾轉(zhuǎn)移到指定文件夾
var?Koa?=?require('koa')
const?getSize?=?require('image-size') // 獲取圖片寬高
var?Router?=?require('koa-router')
var?fs?=?require('fs')
const?koaStatic?=?require('koa-static')
const?path?=?require('path')
var?body?=?require('koa-body')
const?bodyParse?=?require('koa-bodyparser')
const?app?=?new?Koa()
//跨域設置
app.use(
??cors({
????origin: "*",
????maxAge:?5,
????credentials:?true,
????withCredentials:?true,
????allowMethods:?['GET',?'POST'],
????allowHeaders:?['Content-Type',?'Authorization',?'Accept']
??})
)
app.use(koaStatic(path.join(__dirname,?'./upload/')))//設置? 圖片靜態(tài)服務器 設置之后就可以直接訪問http://localhost:4000/male.jpg圖片了
app.use(
??body({
????multipart:?true
??})
)//設置可以多文件上傳
app.use(bodyParse())
var?router?=?new?Router()
router.post('/saveImage',?body(),?async?(ctx,?next)?=>?{
??var?data?=?ctx.request.files.file
??const?dest?=?path.join(__dirname,?'upload',?data.name)
??fsr.move(data.path,?dest)?
??var?width?=?getSize('./upload/'?+?data.name).width
??var?height?=?getSize('./upload/'?+?data.name).height
??let?url?=?'http://localhost:4000/'?+?data.name?+?'?'?+?width?+?'*'?+?height
??ctx.body?=?{
????path:?data.path,
????name:?data.name,
????url:?url
??}
})
app.use(router.routes()).use(router.allowedMethods())
app.listen(4000)
console.log('server?started?at?http://localhost:4000')
結果展示:
在實現(xiàn)過程中?http://www.reibang.com/p/901084d32de2這篇文章給了我很大的幫助
這篇文章解釋的很詳細阎毅。推薦一下焚刚。