1

下面是用于在我的快递应用中上传图片的路线的代码。我正在使用 multer 将其简单地存储在上传文件夹中的应用程序中,但现在正尝试将它们上传到 MongoDb。我现在尝试了几种方法,似乎中间件upload.single('image')没有正确处理文件。我不知道我还能如何解决这个问题。

image.js

const mongoose = require('mongoose');
const {GridFsStorage} = require('multer-gridfs-storage');
const router = require('express').Router();
const multer = require('multer');
const crypto = require('crypto');
const path = require('path');
require('dotenv').config();

const mongoURI = process.env.DB_CONNECTION;

const storage = new GridFsStorage({
    url: mongoURI,
    options: { useUnifiedTopology: true },
    file: (req, file) => {
      return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
          if (err) {
            return reject(err);
          }
          const filename = buf.toString('hex') + path.extname(file.originalname);
          const fileInfo = {
            filename: filename,
            bucketName: 'images',
          };
          resolve(fileInfo);
        });
      });
    },
  });
const upload = multer({ storage });

router.post('/upload/', upload.single('image'), async (req, res) => {
  console.log(req.file);
  const { file } = req;
  const { id } = file;
  if (file.size > 5000000) {
    deleteImage(id);
    return res.status(400).send('file may not exceed 5mb');
  }
  console.log('uploaded file: ', file);
  return res.send(file.id);
});

错误

(node:33883) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property 'id' of 'file' as it is undefined.
    at /Users/abnerpena/Desktop/PReC-website/Backend/routes/image.js:40:11
    at Layer.handle [as handle_request] (/Users/abnerpena/Desktop/PReC-website/Backend/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/abnerpena/Desktop/PReC-website/Backend/node_modules/express/lib/router/route.js:137:13)
    at Immediate.<anonymous> (/Users/abnerpena/Desktop/PReC-website/Backend/node_modules/multer/lib/make-middleware.js:53:37)
    at processImmediate (internal/timers.js:464:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:33883) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:33883) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
POST /api/images/upload - - ms - -
undefined
(node:33883) UnhandledPromiseRejectionWarning: TypeError: Cannot destructure property 'id' of 'file' as it is undefined.
    at /Users/abnerpena/Desktop/PReC-website/Backend/routes/image.js:40:11
    at Layer.handle [as handle_request] (/Users/abnerpena/Desktop/PReC-website/Backend/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/abnerpena/Desktop/PReC-website/Backend/node_modules/express/lib/router/route.js:137:13)
    at Immediate.<anonymous> (/Users/abnerpena/Desktop/PReC-website/Backend/node_modules/multer/lib/make-middleware.js:53:37)
    at processImmediate (internal/timers.js:464:21)
(node:33883) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
4

0 回答 0