如何使用Multer在Node.js服务器中上传文件

时间:2019-05-13 13:27:08

标签: node.js angular multer

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

运行应用程序时,出现以下错误: 错误:请选择文件

HTML:

mobility = TraCIMobilityAccess().get(getParentModule());
string cur = mobility->getRoadId();

这是我的<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);
}

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

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);
}

我的工作代码与无法工作的代码之间的区别在于,如果类型为<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控件,并且当我进行更改时我的代码无法正常工作。

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

1 个答案:

答案 0 :(得分:1)

使用npm install --save multer安装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
})

有关更多信息,您可以阅读文档here