使用具有角度7平均堆栈的multer中间件上传文件不起作用
Posted
技术标签:
【中文标题】使用具有角度7平均堆栈的multer中间件上传文件不起作用【英文标题】:file upload using multer middleware with angular 7 mean stack not working 【发布时间】:2020-03-30 19:22:48 【问题描述】:请,我正在使用 multer 中间件在角度平均堆栈中上传文件。我无法获取 req.file 但可以获取 req.body ,这意味着文件没有被上传。 一开始上传时查看指定的上传文件夹,除了其他文本数据可以进入猫鼬数据库外,我什么也看不到。
然后我尝试 res.send(req.file.filename) 它说找不到未定义的属性“文件名”。当我 res.send(req.file) 它返回 null。但是当我 res.send(req.body) 它返回从 html 表单键入的文本数据。我做错了什么?
我已经在 *** 和其他在线地方针对类似问题提出了许多建议,但没有一个为我解决问题。
请帮忙
在下面的 vehicle.route.js 中找到我的代码:
path = require('path'),
multer = require('multer'),
app = express();
const DIR = '../uploads/';
const storage = multer.diskStorage(
destination: (req, file, cb) =>
cb(null, DIR);
,
filename: (req, file, cb) =>
const fileName = file.fieldname + '-' + Date.now();
cb(null, fileName)
);
let upload = multer(
storage: storage
)
vehicleRouter = express.Router();
// Vehicle model
let Vehicle = require('../models/Vehicle');
app.use(express.static(path.join(__dirname, '../uploads')));
// Get All Employees
vehicleRouter.route('/').get((req, res, next) =>
Vehicle.find((error, data) =>
if (error)
return next(error)
else
res.json(data)
)
)
vehicleRouter.post('/register', upload.single('purchaseReceipt'), (req, res, next) =>
res.json(req.file.filename)
return;
/*vehicleRouter.post('/register', upload.single('purchaseReceipt'), (req, res, next) =>
res.json(req.file)
return;
const vehicle = new Vehicle(
fullName: req.body.fullName,
purchaseReceipt: req.file.filename
);
vehicle.save().then(result =>
console.log(result);
res.status(201).json(
message: "Vehicle registered successfully!",
userCreated:
_id: result._id,
name: result.name,
purchaseReceipt: result.purchaseReceipt
)
)
/*Vehicle.create(req.body, (error, data) =>
if (error)
return next(error)
else
res.json(data)
)*/
//res.json('from register vehicle')
)
app.use(express.static(path.join(__dirname, './uploads')));
module.exports = vehicleRouter;```
I tried uploading straight but it isnt then I commented part of the code and tried to send back req.file.filename as response but it is saying: error: "Cannot read property 'filename' of undefined"
[the error code on console][1]
[1]: https://i.stack.imgur.com/LY9ob.png
vehicle-registration.component.html code ie the html form
```<div class="card">
<div class="card-body">
<form method="post" [formGroup]="vehicleForm" (ngSubmit)="onSubmit()" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-4">Full Name</label>
<input type="text" class="form-control" formControlName="fullName" />
</div>
<div class="form-group">
<div class="preview" *ngIf="preview && preview !== null">
<img [src]="preview" [alt]="vehicleForm.value.name">
</div>
</div>
<!--<div class="form-group">
<label class="col-md-4">Upload Purchase Receipt</label>
<input type="text" class="form-control" formControlName="purchaseReceipt" />
</div>-->
<div class="form-group">
<label class="col-md-4">Upload Purchase Receipt </label>
<input type="file" class="form-control" (change)="uploadFile($event)" formControlName="purchaseReceipt" name="purchaseReceipt"/>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-3">
<button class="btn btn-success btn-sm btn-block" type="submit">Register Vehicle</button>
</div>
</div>
</div>
</form>
</div>
</div>```
vehicle-registration.component.ts code
从'@angular/core'导入组件,OnInit; 从 '@angular/forms' 导入 FormGroup, FormBuilder, Validators ; 从'../../service/vehicle.service'导入 VehicleService;
@组件( 选择器:'应用程序车辆注册', templateUrl: './vehicle-registration.component.html', styleUrls: ['./vehicle-registration.component.css'] ) 导出类 VehicleRegistrationComponent 实现 OnInit 预览:字符串; 车辆形式:FormGroup;
构造函数(公共 fb:FormBuilder,私有 vs:VehicleService) this.createForm()
ngOnInit()
createForm() this.vehicleForm = this.fb.group( 全名:['',[Validators.required]], purchaseReceipt: [null, [Validators.required]], );
上传文件(事件) const file = (event.target as HTMLInputElement).files[0]; this.vehicleForm.patchValue( 头像:档案 ); this.vehicleForm.get('头像') // .updateValueAndValidity()
// File Preview
const reader = new FileReader();
reader.onload = () =>
this.preview = reader.result as string;
reader.readAsDataURL(file)
onSubmit() 如果(!this.vehicleForm.valid) 返回假; 别的 this.vs.registerVehicle(this.vehicleForm.value) 。订阅( (res) => console.log('车辆注册成功!'); 控制台.log(res); , (错误)=> 控制台日志(错误); );
```
服务文件即vehicle.service.ts
import Observable, throwError from 'rxjs';
import catchError, map from 'rxjs/operators';
import HttpClient, HttpHeaders, HttpErrorResponse from '@angular/common/http';
@Injectable(
providedIn: 'root'
)
export class VehicleService
baseUri: string = 'http://localhost:3000/vehicle';
headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private http: HttpClient)
registerVehicle(data): Observable<any>
console.log(data);
const url = `$this.baseUri/register`;
return this.http.post(url, data);
```
【问题讨论】:
您好,您有解决办法吗? 【参考方案1】:您好,您能否发布您的 Angular 代码,以便我们查看您是否真的将文件发送到后端 - nodejs。感谢等待
新的更新!!
对不起,我犯了一个错误的智慧。我应该设置表单数据 在你使用的地方使用 formdata.set..。
let image = new fileReader();
formdata: Formdata = new Formdata(); //updated!!
constructor()
preview($event)
this.image.onloadend = ()=>
//other codes
this.formdata.set("image", $event.target.files[0]); // you can use this.formdata.append(...) if you want, but append keeps adding if maybe there is a retry due to error
this.image.readAsDataURL($event.target.files[0]);
onsubmit()
//append or set other thing
this.vs.registerVehicle(this.formdata).subscribe(d=>
// code here
)
在上传图片时使用 formData 可以更轻松地在后端接收文件。
【讨论】:
我的vehicle-registration.component.html代码即html表单: 我有这个错误:TypeError:无法读取未定义的属性“设置”。它指向我写的代码行:this.formdata.set('purchaseReceipt', this.vehicleForm.value);我还在类中声明了 formdata: FormData以上是关于使用具有角度7平均堆栈的multer中间件上传文件不起作用的主要内容,如果未能解决你的问题,请参考以下文章
nodeJs学习-08 multer中间件,解析post文件,上传文件
在 Express 路由器中使用 multer 进行文件上传