【发布时间】:2020-02-10 05:13:40
【问题描述】:
我不知道为什么,但我的函数在 storage.single 中被调用了两次。
app.post("/upload-file", async (req, res, next) => {
try {
export const inMemoryStorage = (opts = {}) => {
return multer({ storage: multer.memoryStorage(), ...defaultOpts,
...opts })
}
const storage = inMemoryStorage();
storage.single('file')(req, res, () => {
console.log(req.file) // in my last update
console.log('called') // this is returned two times
return this.uploadService.uploadFile(req)
})
} catch (err) {
next(err);
}
});
}
如果您有解决方案,谢谢。我只想让我的函数被调用一次。
---- 新编辑----
所以我的uploadService是这样的:
async uploadFile(req) {
const b2 = new B2({
applicationKeyId: 'private1',
applicationKey: 'private2'
})
const upload = await b2.getUploadUrl({ bucketId: 'my-private-key' })
const myfile = await b2.uploadFile({
uploadUrl: upload.data.uploadUrl,
uploadAuthToken: upload.data.authorizationToken,
fileName: getFilename(req.file),
data: req.file.buffer,
onUploadProgress: (event) => null
})
console.log(myfile) // it works
return myfile
}
所以我的上传工作正常了,我可以看到我的 console.log。所以在我的数据库中,比如第一次上传后的 15 秒,我的方法发送了另一个文件,并且我的 console.log 返回了两次对象
--------- 最后更新 ----------
我注意到一些东西,我不知道为什么,但是当我的文件大于 50mb 时。我的函数被调用了 2 次。在 50mb 以下,一切正常,我只发送一次文件
如您所见,我添加了 console.log(req.file)。结果是:
{
fieldname: 'file',
originalname: 'myMovie.mp4',
encoding: '7bit',
mimetype: 'video/mp4',
buffer: <Buffer 1a 45 df a3 01 00 00 00 00 00 00 23 42 86 81 01 42 f7 81 01 42 f2 81 04 42 f3 81 08 42 82 88 6d 61 74 72 6f 73 6b 61 42 87 81 04 42 85 81 02 18 53 80 ... 107390076 more bytes>,
size: 107390126
}
{
fieldname: 'file',
originalname: 'myMovie.mp4',
encoding: '7bit',
mimetype: 'video/mp4',
buffer: <Buffer 1a 45 df a3 01 00 00 00 00 00 00 23 42 86 81 01 42 f7 81 01 42 f2 81 04 42 f3 81 08 42 82 88 6d 61 74 72 6f 73 6b 61 42 87 81 04 42 85 81 02 18 53 80 ... 107390076 more bytes>,
size: 107390126
}
所以我的两个req.file是一样的
【问题讨论】:
-
你能发布完整的代码吗?例如 - this.uploadService 是什么?
-
您可能必须像每个 JavaScript 用户一样使用分号。它可能会自行修复,前提是您在理论上执行
const storage = inMemoryStorage()storage.single ...。 -
我进行了更新以向您展示我的uploadService。而且我不认为这是我的分号,因为它在两行。但我添加了一个只是为了确定