From 48adde820ef29ffe58d5b452cd6c7f98c54da4c6 Mon Sep 17 00:00:00 2001 From: Luk Lu Date: Sat, 30 Dec 2023 13:22:23 +0800 Subject: [PATCH] u --- fileloader.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/fileloader.js b/fileloader.js index 9a04f51..9ad7b6a 100644 --- a/fileloader.js +++ b/fileloader.js @@ -6,8 +6,10 @@ const wo = global.wo const my = {} module.exports = { - initMy ({ ipfsProvider }) { + initMy ({ ipfsProvider, ipfsStore }) { my.ipfsProvider = ipfsProvider + my.ipfsStore = ipfsStore + return this }, MulterStore: multer({ @@ -24,7 +26,7 @@ module.exports = { // 虽然可以把本方法写成 async 的,并且在这里调用 wo.ipfsStore.ipfs.add(file.stream) 来获取 cid,但是最后在本地存成的文件是 0字节的。因此还是用个随机数吧。 // 或者,干脆利用这个缺陷,直接提交到 ipfs,在本地就留着0字节文件不要使用就好了。同时,在 api.receiveFile 里,就要相应的直接返回 IPFS 网址给前端。 const filename = - `${Date.now()}-${crypto.randomBytes(16).toString('hex')}` + (path.extname(file.originalname) || `.${file?.mimetype?.split?.('/')?.[1]}`) + `${Date.now()}-${crypto.randomBytes(16).toString('hex')}` + (path.extname(file.originalname || '') || `.${file?.mimetype?.split?.('/')?.[1]}`) //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) @@ -38,13 +40,14 @@ module.exports = { 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 || global.wo?.ipfsProvider + const ipfsStore = my.ipfsStore || global.wo?.ipfsStore if (_file?.path) { _file.path = _file.path.replace('\\', '/') - _file.baseUrl = `${global.wo?.envar?.servUrl?.replace?.(/\/$/, '')}/${path}` // 传统的基于服务器的 url。在开发环境下,不一定符合前端实际,因为后台只知道预设的 servUrl,而前端会再根据 location.origin 来调整。 - if (useIpfs && wo?.ipfsStore) { + _file.baseUrl = `${global.wo?.envar?.servUrl?.replace?.(/\/$/, '')}/${_file.path}` // 传统的基于服务器的 url。在开发环境下,不一定符合前端实际,因为后台只知道预设的 servUrl,而前端会再根据 location.origin 来调整。 + if (useIpfs && 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 global.wo?.ipfsStore?.add?.(ipfsProvider.globSource(_file.path, ''), { + const { cid } = await ipfsStore?.add?.(ipfsProvider.globSource(_file.path, ''), { // __dirname 是本文件所在目录,但 path.resolve(_file.path) 得到的是正确路径。 // 20230713 不知为何,今天在本机测试时,ipfs-core 报错 Pattern must be a string,之前没有过这个问题。跟踪后发现 ipfs-core 0.14.3 代码里 第二个参数 patter 必须是 string,于是添加第二个参数为 '',现在可以上传文件给本地的 ipfs-core 了。经测试,加不加这个参数都不影响 ipfs-http-client 运行。 cidVersion: 1,