添加一个 useIpfs 参数

This commit is contained in:
陆柯 2023-10-13 14:15:42 +08:00
parent 4cdf05f62c
commit 397ffa4aba

View File

@ -35,12 +35,13 @@ module.exports = {
}).single('file'),
api: {
async receiveFile ({ _file = wo?._req?.file } = {}) {
// req 被 multer 处理后req.file 为 { destination, filename, originialname, path, mimetype, size }, 其中 path 包括了 destination 和 filename 的文件相对路径
async receiveFile ({ _file = wo?._req?.file, useIpfs = true } = {}) {
// req 被 multer 处理后req.file 为 { destination, filename, originialname, path, mimetype, size }, 其中 path 包括了 destination 和 filename 的文件相对路径,但不包括起头的 '/',例如 '_filestore/xxx.png'
const ipfsProvider = my.ipfsProvider || wo?.ipfsProvider
if (_file?.path) {
_file.path = _file.path.replace('\\', '/')
if (wo?.ipfsStore) {
_file.baseUrl = `${wo.envar.servUrl}/${path}` // 传统的基于服务器的 url。在开发环境下不一定符合前端实际因为后台只知道预设的 servUrl而前端会再根据 location.origin 来调整。
if (useIpfs && wo?.ipfsStore) {
// 为了在这里使用 wo.ipfsStore.add, 需要提供 FileContent不能直接用 req.file
// 20230312: not working with nodejs above (not including) 18.2.1! https://github.com/nodejs/node/issues/46221
const { cid } = await wo.ipfsStore.add(ipfsProvider.globSource(_file.path, ''), {
@ -51,8 +52,7 @@ module.exports = {
pin: false, // 用户第一次上传的,可能并不是最后想要的,不必须永存。
})
_file.cid = cid?.toString() // + path.extname(file.filename)
_file.ipfsUrl = wo.envar.ipfsGateway + _file.cid
// file.path = wo.envar.ipfsGateway + file.cid // 可选考虑直接返回 ipfs地址。在本地测试成功但是发现第一次上传的文件作为ipfs网关图片在前端显示比较慢不如显示http的快。第二次上传同样文件的ipfs前端显示就快了。
_file.ipfsUrl = wo.envar.ipfsGateway + _file.cid // 1) 前端自己选用 cid 或 ipfsUrl。2) 在本地测试成功,但是发现第一次上传的文件,作为 ipfs url 图片在前端显示比较慢不如作为传统服务器的快。第二次上传同样文件的ipfs前端显示就快了。
}
return { _state: 'SUCCESS', ..._file }
} else {