生活随笔
收集整理的這篇文章主要介紹了
Egg.js上传图片总结
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
使用form表單
前端代碼
<form action
="http://127.0.0.1:7001/headPicUpdate" method
="post" encType
="multipart/form-data"><input type
="file" name
="file" /><input type
="submit" value
="上傳" />
</form
>
后端代碼
'use strict';
const Controller
= require('egg').Controller
;class userInfoUpdateController extends Controller {async headPicUpdate() { const path
= require('path')const fs
= require('fs')const { ctx
} = this; let userId
= this.ctx
.request
.body
.userId
const file
= ctx
.request
.files
[0]const toFileName
= '/public/upload/' + Date
.now() + file
.filename
;const to
= path
.dirname(__dirname
) + toFileName
;await fs
.copyFileSync(file
.filepath
, to
)const newUrl
= "http://127.0.0.1:7001" + toFileName
;const results
= await this.app
.mysql
.query('update user set headPicPath = ? where userId = ?', [newUrl
, userId
]);ctx
.body
= {msg: '圖片上傳成功',url: newUrl
}}
}module
.exports
= userInfoUpdateController
;
3.上傳結(jié)果
使用axios發(fā)送請求
前端代碼
圖片上傳:
<input id
="uploadFile" type
="file" name
="file" />上傳按鈕:
<button type
="submit" onClick
={upload
}>Upload
</button
>
const upload = () => {let file
= document
.querySelector('#uploadFile').files
[0]let formData
= new FormData()let userId
= localStorage
.getItem('userId')formData
.append("uploadFile", file
)formData
.append("userId", userId
)axios
.post(servicePath
.headPicUpdate
, formData
).then(function (response) {localStorage
.setItem('headPicPath',response
.data
.url
)navigate('/index/my/myDetail')console
.log(response
);}).catch(function (error) {console
.log(error
);});}
后端代碼
'use strict';
const Controller
= require('egg').Controller
;class userInfoUpdateController extends Controller {async headPicUpdate() { const path
= require('path')const fs
= require('fs')const { ctx
} = this; let userId
= this.ctx
.request
.body
.userId
const file
= ctx
.request
.files
[0]const toFileName
= '/public/upload/' + Date
.now() + file
.filename
;const to
= path
.dirname(__dirname
) + toFileName
;await fs
.copyFileSync(file
.filepath
, to
)const newUrl
= "http://127.0.0.1:7001" + toFileName
;const results
= await this.app
.mysql
.query('update user set headPicPath = ? where userId = ?', [newUrl
, userId
]);ctx
.body
= {msg: '圖片上傳成功',url: newUrl
}}
}module
.exports
= userInfoUpdateController
;
上傳結(jié)果
需要注意的點(diǎn)
使用form表單的時候,input框要添加name屬性,否則后端ctx.request.files[0]為空
<input type
="file" name
="file" />
上傳multipart/form-data格式的文件,后端在config\config.default.js文件添加如下配置
config
.multipart
= {mode: 'file'};
參考資料:
1. egg.js文檔
2. axios文檔
總結(jié)
以上是生活随笔為你收集整理的Egg.js上传图片总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。