wo-base-fileloader/index.js
2021-10-20 16:37:19 +08:00

43 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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会负责创建该目录。如果提供函数你要负责确保该目录存在。
const folder = wo?.envi?.uploadroot // 目录是相对于本应用的入口js的即相对于 server.js 的位置。
cb(null, folder)
},
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(32).toString('hex')}${fileNameExtension}`
//const _passtokenSource = webtoken.verifyToken(req.headers._passtoken, wo.envi.tokenKey) || {}
//const filename = `${req.path.replace(/^\/api\d*/, '')}_${_passtokenSource.uuid}_${Date.now()}${fileNameExtension}` // 如果最终 filename 含有 / (例如当 req.path 为 Who/todo则必须已经存在该目录否则在这里就出错不会进入下面流程。
cb(null, filename)
},
// req 被 multer 处理后req.file 为 { filename, originialname, path, mimetype, size }
}),
// fileFilter:function(req, file, cb) {},
limits: { fileSize: 10485760 },
}).single('file'),
api: {
receiveFile () {
const file = wo._req?.file
if (file?.path) {
file.path = file.path.replace('\\', '/')
return Object.assign(file, { _state: 'SUCCESS' })
} else {
return { _state: 'BACKEND_FAIL_FILE_NOT_RECEIVED' }
}
}
}
}