首页 > 解决方案 > 为什么我的函数在 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 是一样的

标签: node.jsmulter

解决方案


我想我在您更新的代码示例中看到了问题。您没有在路由处理程序中将响应发送回客户端,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);
        }
     });
}

推荐阅读