Egg.js上传图片总结

使用form表单

  1. 前端代码
<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>
  1. 后端代码
'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.上传结果
在这里插入图片描述

使用axios发送请求

  1. 前端代码
 图片上传:<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);
        });
    }
  1. 后端代码
'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;
  1. 上传结果
    在这里插入图片描述

需要注意的点

  1. 使用form表单的时候,input框要添加name属性,否则后端ctx.request.files[0]为空
	<input type="file" name="file" />
  1. 上传multipart/form-data格式的文件,后端在config\config.default.js文件添加如下配置
 config.multipart = {
    mode: 'file'
  };

参考资料:

1. egg.js文档
2. axios文档

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值