Commit f9200425b0b21f213a6c334557cb39beeb390a61
1 parent
82b13adb
Exists in
master
增加文件上传功能
Showing
5 changed files
with
43 additions
and
2 deletions
Show diff stats
| ... | ... | @@ -0,0 +1,28 @@ |
| 1 | +'use strict'; | |
| 2 | + | |
| 3 | +const fs = require('fs'); | |
| 4 | +const path = require('path'); | |
| 5 | +const Controller = require('egg').Controller; | |
| 6 | +const awaitWriteStream = require('await-stream-ready').write; | |
| 7 | +const sendToWormhole = require('stream-wormhole'); | |
| 8 | +const uuid = require('node-uuid'); | |
| 9 | + | |
| 10 | +class FileController extends Controller { | |
| 11 | + | |
| 12 | + async upload() { | |
| 13 | + const stream = await this.ctx.getFileStream(); | |
| 14 | + const filename = uuid.v1() + path.extname(stream.filename).toLowerCase(); | |
| 15 | + const target = path.join(this.config.baseDir, 'app/public', filename); | |
| 16 | + const writeStream = fs.createWriteStream(target); | |
| 17 | + try { | |
| 18 | + await awaitWriteStream(stream.pipe(writeStream)); | |
| 19 | + } catch (err) { | |
| 20 | + await sendToWormhole(stream); | |
| 21 | + throw err; | |
| 22 | + } | |
| 23 | + | |
| 24 | + this.ctx.body = { url: '/public/' + filename }; | |
| 25 | + } | |
| 26 | +} | |
| 27 | + | |
| 28 | +module.exports = FileController; | ... | ... |
app/router.js
| ... | ... | @@ -8,6 +8,8 @@ module.exports = app => { |
| 8 | 8 | router.get('/', controller.home.index); |
| 9 | 9 | // 首页统计 |
| 10 | 10 | router.get('/statistic/count', controller.statistic.count); |
| 11 | + // 文件上传 | |
| 12 | + router.post('/file/upload', controller.file.upload); | |
| 11 | 13 | // 用户管理 |
| 12 | 14 | router.post('/user/password', controller.user.password); |
| 13 | 15 | router.post('/user/validate', controller.user.validate); | ... | ... |
app/service/contract.js
| ... | ... | @@ -11,7 +11,6 @@ class ContractService extends Service { |
| 11 | 11 | select contract.*, user.name as manager_name from contract, user where contract.manager_id = user.id |
| 12 | 12 | ${where !== '' ? `and ${where}` : ''} |
| 13 | 13 | `; |
| 14 | - console.log(sql); | |
| 15 | 14 | const result = await this.app.mysql.query(sql); |
| 16 | 15 | return result; |
| 17 | 16 | } | ... | ... |
config/config.default.js
package.json
| ... | ... | @@ -9,7 +9,9 @@ |
| 9 | 9 | "egg-mysql": "^3.0.0", |
| 10 | 10 | "egg-scripts": "^2.5.0", |
| 11 | 11 | "moment": "^2.22.1", |
| 12 | - "node-uuid": "^1.4.8" | |
| 12 | + "node-uuid": "^1.4.8", | |
| 13 | + "await-stream-ready": "^1.0.1", | |
| 14 | + "stream-wormhole": "^1.0.3" | |
| 13 | 15 | }, |
| 14 | 16 | "devDependencies": { |
| 15 | 17 | "autod": "^3.0.1", | ... | ... |