{ try -6ren">
gpt4 book ai didi

node.js - 为什么我的函数在 storage.single 中被调用两次?

转载 作者:行者123 更新时间:2023-12-02 10:26:00 24 4
gpt4 key购买 nike

我不知道为什么,但我的函数在 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 是相同的

最佳答案

我想我在您更新的代码示例中看到了问题。您没有在 upload-file 路由处理程序中将响应发送回客户端,这会导致浏览器重新发送请求。

修改处理程序如下

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
await this.uploadService.uploadFile(req);
res.sendStatus(200); // or equivalent
})
} catch (err) {
next(err);
}
});
}

关于node.js - 为什么我的函数在 storage.single 中被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59974635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com