node.js - 如何使用 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
控件,当我进行那个更改时我的代码不起作用。
有人可以告诉我如何使用此控件来传递文件吗?提前非常感谢!
解决方案
使用安装 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
})
有关更多信息,您可以在此处阅读文档
推荐阅读
- json - 动态创建一个从我的本地 JSON 文件夹中获取数据的配置文件页面
- python - 写入 csv 并上传到 S3 的 Lambda 函数
- php - 尝试使用 php 和 ajax 和 jquery 上传图像时出现 500 错误
- ios - IBOutlet Autolayout 约束常量变化
- sql-server - 如何根据作业名称批量更新 SQL Server 代理作业重试尝试
- django - 你能用 formset 管理两个离散的表单吗?
- python - ValueError:发现样本数量不一致的输入变量:[29675、9574、29675]
- python - Spark Arrow、toPandas() 和宽变换
- javascript - 结合两个 mapStateToProps React
- javascript - 如何使用 Lodash 搜索和过滤嵌套属性?