rename npm/basend-fileload-server to npm/basend-fileloader

This commit is contained in:
luk.lu
2022-07-23 08:18:48 +08:00
parent 383235168d
commit c993703471
2 changed files with 2 additions and 1 deletions

39
fileloader.js Normal file
View File

@@ -0,0 +1,39 @@
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.uuid}_${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: {
receiveFile () {
const file = wo._req?.file
if (file?.path) {
file.path = file.path.replace('\\', '/')
return Object.assign(file, { _state: 'SUCCESS' })
} else {
return { _state: 'BASEND_FAIL_FILE_NOT_RECEIVED' }
}
},
},
}