gpt4 book ai didi

javascript - "TypeError: Cannot read property ' filename ' of undefined "使用multer上传用户头像

转载 作者:行者123 更新时间:2023-12-05 06:54:53 28 4
gpt4 key购买 nike

我正在尝试使用 express.js 服务器和 Multer 上传用户个人资料照片,但不知道为什么会出现“类型错误:无法读取未定义的属性‘文件名’”错误。下面是我的服务器和 html 代码。

导入包

   const multer= require('multer');
const path=require('path');
const express=require('express');
const app=express();
app.use(express.json());
app.use(cors());

中间件代码

      app.use(express.static( __dirname+"./backend/database/"));

var upload=multer({dest:'public/'});

var upload=multer({
storage:multer.diskStorage({
destination:function(req,file,cb){
cb(null,'./public');
},
filename:(req,file,cb)=>{ cb(null,file.originalname);
}
})
}).single('Image')

注册用户的API

    app.post('/register',upload,(req,res)=>{
let userData ={
Name:req.body.Name,
Password:req.body.Password,
Username:req.body.Username,
ContactNo:req.body.ContactNo,
Image:req.file.filename
}
console.log(req.body);//to check if image successfully recieved from the frontend
})

HTML代码

     <form [formGroup]="register" (ngSubmit)="Register(register.value)" enctype="multipart/form-data" >
<legend>
Sign Up
</legend>
<mat-form-field color="warn">
<mat-label>Name</mat-label>
<mat-icon >person</mat-icon>
<input matInput type="email" formControlName="Username" value="Username" />
</mat-form-field>

<mat-form-field color="warn">
<mat-label>Enter your Email</mat-label>
<mat-icon >email</mat-icon>
<input matInput type="email" formControlName="Name" value="Email" />
</mat-form-field>

<mat-form-field color="warn">
<mat-label>Phone Number</mat-label>
<mat-icon >call</mat-icon>
<input matInput type="number" formControlName="ContactNo" placeholder="+91 XXXXXXXXXX"
value="ContactNo" />
</mat-form-field>

<mat-form-field color="warn">
<mat-label>Write your Password</mat-label>
<mat-icon >lock</mat-icon>
<input matInput formControlName="Password" placeholder="Password" type="password" />
</mat-form-field>

<div color="warn">
<label>Upload Your Photo</label>
<mat-icon >photo</mat-icon>
<input class="file" formControlName="Image" placeholder="Upload Image" type="file" />
</div>
<button mat-raised-button color="warn" type="submit" (click)="changeAgain()">submit</button>
<button mat-raised-button color="primary" style="margin-top: 2px;" type="reset">Reset</button>
<br>
</form>

发布数据

     Register(data)
{
this.serve.RegisterUser(data);
//" serve " here is alias for injected HTTP services
}

最佳答案

这是错误来源:

      Image:req.file.filename

因为你没有设置 multer 中间件。

app.use(multer({ storage: fileStorage, fileFilter }).single("image")); 

当你设置这个时,multer 会将'file'对象附加到“req”。目前req.file未定义

关于javascript - "TypeError: Cannot read property ' filename ' of undefined "使用multer上传用户头像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65440907/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com