首页 > 解决方案 > 如何使用 multer 在 node.js 服务器中上传文件

问题描述

我正在尝试将文件从我的 Angular 应用程序传递到 node.js 服务器。

当我运行应用程序时,我收到以下错误:错误:请选择文件

HTML:

<upload name="fileUpload" formControlName="fileUpload" #fileUpload (listChange)="updateList($event)" data-kind="primary"
          [imagePreview]="true">
</upload>

这是我的updateList()方法:

updateList(list: any) {
    this.demolist = Array.apply(this, list);
    this.attachmentReady.emit(this.demolist);
}

节点:

const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const multer = require('multer');
let nodemailer = require('nodemailer');
let aws = require('aws-sdk');
const fs = require('fs');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
});

var upload = multer({ storage: storage });

app.post('/postData', upload.array('fileUpload', 12), (req, res, next) => {
    console.log(req.body);
    res.json(req.body);

    const files = req.files
    if (!files) {
        const error = new Error('Please choose files')
        error.httpStatusCode = 400
        return next(error)
    }
    res.send(files);
}

在另一个项目中,multer 按预期工作。以下是该项目的 HTML:

<form action="/uploadmultiple" enctype="multipart/form-data" method="POST">
    Select images: <input type="file" name="myFiles" multiple>
    <input type="submit" value="Upload your files" />
</form>

我的工作代码和不工作的代码之间的区别在于,input如果类型是file. 但是我现在需要使用一个upload控件,当我进行那个更改时我的代码不起作用。

有人可以告诉我如何使用此控件来传递文件吗?提前非常感谢!

标签: node.jsangularmulter

解决方案


使用安装 multer 后npm install --save multer

基本用法示例:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/uploadmultiple', upload.single('myFiles'), function (req, res, next) {
  // req.file is the `myFiles ` file
  // req.body will hold the text fields, if there were any
})

app.post('/uploadmultiple', upload.array('myFiles', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

有关更多信息,您可以在此处阅读文档


推荐阅读