使用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.userIdconst 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.上传结果
使用axios发送请求
前端代码图片上传:<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.userIdconst 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;
上传结果
需要注意的点
使用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文档