【问题标题】:Uploading files with Angular and nodejs multer使用 Angular 和 nodejs multer 上传文件
【发布时间】:2021-11-04 00:04:37
【问题描述】:

我正在尝试将文件从 angular 11 上传到 nodejs multer,但我得到未定义

htlm file the typesScrip code

我的 multer 配置 const multer = require('multer');

/**  */
const storage = multer.diskStorage({
 destination: (req, file, callback) => {
 callback(null, 'files');
 },
 filename: (req, file, callback) => {
 const name = file.originalname.split(' ').join('_');
 //const extension = MIME_TYPES[file.mimetype];+ '.' + extension
 callback(null, name + Date.now() );
 }
});
 
module.exports = multer({storage: storage}).single('file');

这是我的路线代码

const express = require('express');
const router = express.Router();


const upload = require('../middleware/multerConfig')

router.post('/test', upload, async(req, res, next) => {
  console.log(req.body)
  console.log(req.file)
  }
);

和控制台的结果

MongoDB Connected
::ffff:192.168.23.101 - - [03/Nov/2021:14:41:01 +0000] "OPTIONS /api/test HTTP/1.1" 200 8
{ file: {} }
undefined
(node:13444) UnhandledPromiseRejectionWarning: TypeError: Cannot read 
property 'file' of undefined

【问题讨论】:

    标签: node.js angular multer


    【解决方案1】:

    我的方法,根据 multer 的文档,你必须添加这个:

    const express = require('express');
    const router = express.Router();
    
    
    const upload = require('../middleware/multerConfig')
    
    function fileUpload(req, res, next) {
        upload.single('file')(req, res, next);
    }
    
    router.post('/test', fileUpload, async(req, res, next) => {
      console.log(req.body)
      console.log(req.file)
      }
    );
    

    希望能解决

    【讨论】:

    • 谢谢你的回答,你的经历
    • 天哪:)
    猜你喜欢
    • 1970-01-01
    • 2018-07-21
    • 2020-12-31
    • 1970-01-01
    • 2017-03-29
    • 2017-10-28
    • 2021-08-16
    • 2018-08-01
    • 2021-09-02
    相关资源
    最近更新 更多