rename the file to the cid
This commit is contained in:
		
							parent
							
								
									d1f935881b
								
							
						
					
					
						commit
						e79240db0f
					
				| @ -1,5 +1,6 @@ | ||||
| const multer = require('multer') | ||||
| const path = require('path') | ||||
| const fs = require('fs') | ||||
| const crypto = require('crypto') | ||||
| const wo = global.wo | ||||
| 
 | ||||
| @ -26,7 +27,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 || '').toLowerCase() || `.${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) | ||||
| @ -57,11 +58,25 @@ module.exports = { | ||||
|           }) | ||||
|           _file.cid = cid?.toString() // + path.extname(file.filename)
 | ||||
|           _file.ipfsUrl = `${global.wo?.envar?.ipfsGateway?.replace?.(/\/$/, '')}/${_file.cid}` // 1) 前端自己选用 cid 或 ipfsUrl。2) 在本地测试成功,但是发现第一次上传的文件,作为 ipfs url 图片在前端显示比较慢,不如作为传统服务器的快。第二次上传同样文件的ipfs前端显示就快了。
 | ||||
|           // rename the file to the cid
 | ||||
|           const newFileName = `${_file.cid}${path.extname(_file.filename)}` | ||||
|           try { | ||||
|             await fs.renameSync( | ||||
|               path.resolve(_file.path), | ||||
|               path.resolve(_file.destination, newFileName) | ||||
|             ) | ||||
|             // set all properties of _file containing the original file name to the new file name
 | ||||
|             _file.path = _file.path?.replace?.(_file.filename, newFileName) | ||||
|             _file.baseUrl = _file.baseUrl?.replace?.(_file.filename, newFileName) | ||||
|             _file.filename = newFileName | ||||
|           } catch (e) { | ||||
|             console.log('FileLoader: rename failed: ', path.resolve(_file.filename), e) | ||||
|           } | ||||
|           return { _state: 'SUCCESS', ..._file } | ||||
|         } else { | ||||
|           return { _state: 'WOBASE_FAIL_FILE_NOT_RECEIVED' } | ||||
|         } | ||||
|     }, | ||||
|       } | ||||
|     }, | ||||
|   } | ||||
| } | ||||
|  | ||||
		Loading…
	
		Reference in New Issue
	
	Block a user