|
1 | 1 | const { Uploader } = require('lin-mizar/lin/file'); |
| 2 | +const { File } = require('lin-mizar'); |
| 3 | +const { config } = require('lin-mizar/lin/config'); |
2 | 4 | const fs = require('fs'); |
| 5 | +const path = require('path'); |
| 6 | +const { cloneDeep } = require('lodash'); |
3 | 7 |
|
4 | 8 | class LocalUploader extends Uploader { |
5 | 9 | /** |
6 | 10 | * 处理文件流 |
7 | 11 | * @param {object[]} files 文件流数组 |
8 | 12 | */ |
9 | 13 | async upload (files) { |
| 14 | + const arr = []; |
10 | 15 | for (const stream of files) { |
11 | | - const filepath = this.getStorePath(stream.filename); |
12 | | - const target = fs.createWriteStream(filepath); |
13 | | - await stream.pipe(target); |
| 16 | + // 由于stream的特性,当读取其中的数据时,它的buffer会被消费 |
| 17 | + // 所以此处深拷贝一份计算md5值 |
| 18 | + const tmpStream = cloneDeep(stream); |
| 19 | + const md5 = this.generateMd5(tmpStream); |
| 20 | + const siteDomain = config.getItem('siteDomain', 'http://localhost'); |
| 21 | + // 检查md5存在 |
| 22 | + const exist = await File.findOne({ |
| 23 | + where: { |
| 24 | + md5: md5 |
| 25 | + } |
| 26 | + }); |
| 27 | + if (exist) { |
| 28 | + arr.push({ |
| 29 | + key: stream.fieldname, |
| 30 | + id: exist.id, |
| 31 | + url: `${siteDomain}/assets/${exist.path}` |
| 32 | + }); |
| 33 | + } else { |
| 34 | + const { absolutePath, relativePath, realName } = this.getStorePath( |
| 35 | + stream.filename |
| 36 | + ); |
| 37 | + const target = fs.createWriteStream(absolutePath); |
| 38 | + await stream.pipe(target); |
| 39 | + const ext = path.extname(realName); |
| 40 | + // stream.filename tream.filedname stream.mimeType stream.readableLength |
| 41 | + const saved = await File.createRecord( |
| 42 | + { |
| 43 | + path: relativePath, |
| 44 | + // type: 1, |
| 45 | + name: realName, |
| 46 | + extension: ext, |
| 47 | + size: stream.readableLength, |
| 48 | + md5: md5 |
| 49 | + }, |
| 50 | + true |
| 51 | + ); |
| 52 | + arr.push({ |
| 53 | + key: stream.fieldname, |
| 54 | + id: saved.id, |
| 55 | + url: `${siteDomain}/assets/${saved.path}` |
| 56 | + }); |
| 57 | + } |
14 | 58 | } |
| 59 | + return arr; |
15 | 60 | } |
16 | 61 | } |
17 | 62 |
|
|
0 commit comments