50 lines
2.4 KiB
JavaScript
50 lines
2.4 KiB
JavaScript
const multer = require('multer')
|
||
const path = require('path')
|
||
const crypto = require('crypto')
|
||
const wo = global.wo
|
||
|
||
module.exports = {
|
||
MulterStore: multer({
|
||
// dest:'./File/', // 这样,不能自定义文件名。
|
||
storage: multer.diskStorage({
|
||
destination (req, file, cb) {
|
||
// 如果直接提供字符串,multer会负责创建该目录。如果提供函数,你要负责确保该目录存在。
|
||
cb(null, wo?.envar?.fileStore) // 目录是相对于本应用的入口js的,即相对于 server.js 的位置。
|
||
},
|
||
filename (req, file, cb) {
|
||
// 注意,req.body 也许还没有信息,因为这取决于客户端发送body和file的顺序。必要的信息请从 req.headers 传递,例如 _passtoken(在multer时,尚未进入路由,不存在已装好的 _passtokenSource)
|
||
const fileNameExtension = path.extname(file.originalname)
|
||
const filename = `${Date.now()}_${crypto.randomBytes(16).toString('hex')}${fileNameExtension}`
|
||
//const _passtokenSource = webtoken.verifyToken(req.headers._passtoken) || {}
|
||
//const filename = `${req.path.replace(/^\/api\d*/, '')}_${_passtokenSource.usid}_${Date.now()}${fileNameExtension}` // 如果最终 filename 含有 / (例如当 req.path 为 Who/todo),则必须已经存在该目录,否则在这里就出错,不会进入下面流程。
|
||
cb(null, filename)
|
||
},
|
||
// req 被 multer 处理后,req.file 为 { destination, filename, originialname, path, mimetype, size }, 其中 path 包括了 destination 和 filename 的文件完整路径。
|
||
}),
|
||
// fileFilter:function(req, file, cb) {},
|
||
limits: { fileSize: 10485760 },
|
||
}).single('file'),
|
||
|
||
api: {
|
||
async receiveFile () {
|
||
const file = wo._req?.file
|
||
if (file?.path) {
|
||
file.path = file.path.replace('\\', '/')
|
||
if (wo?.ipfsStore) {
|
||
const ipfsResult = await wo.ipfsStore.add(file, {
|
||
cidVersion: 1,
|
||
hashAlg: 'sha2-256',
|
||
onlyHash: true,
|
||
pin: false,
|
||
})
|
||
file.cid = ipfsResult?.cid?.toString() // + path.extname(file.filename)
|
||
file.ipfsUrl = wo.envar.ipfsGateway + file.cid
|
||
}
|
||
return { _state: 'SUCCESS', ...file }
|
||
} else {
|
||
return { _state: 'WOBASE_FAIL_FILE_NOT_RECEIVED' }
|
||
}
|
||
},
|
||
},
|
||
}
|