# 前言
Egg实现图片上传
- 首先前端调用上传接口,将上传的资源经过 FormData 实例封装之后,传给服务端
- 在服务端接收前端传进来的图片信息,通过 fs.readFileSync 方法,来读取图片内容,并存放在变量中
- 找个存放图片的公共位置
- 通过 fs.writeFileSync 方法,将图片内容写入公共位置
- 最后返回图片地址上传到数据库
一、数据库建表
1.数据库建表,表结构为
1 2 3 4 5 6
| CREATE TABLE `img` ( `id` int(10) NOT NULL AUTO_INCREMENT, `imgurl` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT '图片url', `filename` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '图片名称', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=210 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
|
二、egg实现图片上传
1.安装依赖
mkdirp
是一款在 node.js 中像 mkdir -p 一样递归创建目录及其子目录。
Moment.js
是一个轻量级的 JavaScript 时间库,它方便了日常开发中对时间的操作,提高了开发效率。
2.打开 config -> config.defalut.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const path = require('path');
config.uploadDir = 'app/public/upload' config.multipart = { mode: 'file', fileSize: 1048576000, whitelist: [ '.txt', '.png', '.jpg' ], };
config.static = { prefix: '/app/public', dir: path.join(appInfo.baseDir, 'app/public'), dynamic: true, preload: false, maxAge: 31536000, buffer: true, };
|
3.新建controller -> upload.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| 'use strict';
const fs = require('fs'); const moment = require('moment'); const mkdirp = require('mkdirp'); const path = require('path');
const Controller = require('egg').Controller;
class UploadController extends Controller { async upload() { const { ctx } = this; const file = ctx.request.files[0]; let uploadDir = ''; let id = ''; let api = ''; try { const f = fs.readFileSync(file.filepath); const day = moment(new Date()).format('YYYYMMDD'); const dir = path.join(this.config.uploadDir, day); const date = Date.now(); await mkdirp(dir); uploadDir = path.join(dir, date + path.extname(file.filename)); api="http://localhost:7001/" id = await ctx.service.upload.add({ img_url: api + uploadDir, filename: file.filename }); console.log( id); fs.writeFileSync(uploadDir, f); } catch (e) { console.log('error', e); ctx.cleanupRequestFiles(); }
ctx.body = { status: 200, msg: '上传成功', data: api + uploadDir, id, }; } }
module.exports = UploadController;
|
4.新建 service -> upload.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| 'use strict'; const Service = require('egg').Service; class UploadService extends Service { async query(params) { const { app } = this; try { const result = await app.mysql.get('img', params); return result; } catch (error) { console.log(error); return null; } } async add(params) { const { app } = this; try { const result = await app.mysql.insert('img', params); return result.insertId; } catch (error) { return null; } } } module.exports = UploadService;
|
5.最后在 router.js 中加入
1
| router.post('/api/upload/upload',controller.upload.upload;
|
6.发送接口请求数据
数据库插入一条数据
本地查看图片
在使用egg的上传图片功能的时候出现的这个报错:Cannot read properties of undefined (reading ‘0‘)
请查看这篇文章:传送口