node.js - 为什么我的函数在 storage.single 中被调用两次?
问题描述
我不知道为什么,但我的函数在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);
}
});
}
推荐阅读
- vue.js - NW.js (node-webkit) 和 Vue.js 问题与需要系统信息模块
- kotlin - 在 Kotlin 回调流构建器中捕获异常
- exchangewebservices - 需要一个 Element 类型的元素节点“soap:Header”,但找到了 Element 类型的节点“s:Body”
- sql - SQL 查找不同列中的重复项
- python - 创建一个按字母顺序查找最长字符子串的 Python 程序
- ios - 如何使用紧凑型地图功能从 Firebase 的 Cloud Firestore 中检索和建模数据?我试过了,我的代码不起作用
- flutter - 使用底部导航栏在应用购买中颤动
- autofac - 如何在不注册类型对象的情况下解决开放的通用服务?
- python - PySpark 窗口功能改进
- c++ - C++ | 编译 LOG4CXX 和 APR