gpt4 book ai didi

node.js - 上传带有标题的图片

转载 作者:行者123 更新时间:2023-12-03 13:49:15 25 4
gpt4 key购买 nike

我想使用 React、nodejs 和express 将数据上传到 mongoDb。我写了一个代码,但是当我附加图像时,它会显示一个错误,但没有图像数据将存储在数据库中

这是我的 React 代码......

import React, { Component } from "react";
import { Link, Redirect } from "react-router-dom";
import axios from 'axios';

class Register extends Component {
state = {
name: "",
email: "",
password: "",
password2: "",
errors: null,
image: null,
imageName: null
};

onChange = e => {
this.setState({
...this.state,
[e.target.name]: e.target.value
});
};

onChangeImage = async(e) =>{
console.log(e.target.files[0].name);
await this.setState({
...this.state,
image: e.target.files[0],
imageName: e.target.files[0].name
});
}

onSubmit = async e => {

e.preventDefault();
this.setState({
errors: null
});
if (this.state.password !== this.state.password2) {
this.setState({
errors: "Password and Confirm Password Are Invalid"
});
} else {


try {
const config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
let fd = new FormData();
fd.append('image', this.state.image);
const newUser = {
email: this.state.email,
password: this.state.password,
name: this.state.name,
image: fd,
};
console.log(this.state.image);
const body = newUser;
const res = await axios.post('api/addUser', body, config);

console.log(res.data);
} catch (error) {
console.log(error.message);
}
}
};

Alert = () => {
if (this.state.errors != null) {
return <p className="alert alert-danger">{this.state.errors}</p>;
}
return null;
};

render() {
return (
<div>
<h1 className="large text-primary">Sign Up</h1>
<p className="lead">
<i className="fa fa-user" /> Create Your Account
</p>

<form className="form" onSubmit={e => this.onSubmit(e)}
encType="multipart/form-data">
<div className="form-group">
<input
type="text"
placeholder="Name"
name="name"
value={this.state.name}
onChange={e => this.onChange(e)}
/>
</div>
<div className="form-group">
<input
type="email"
placeholder="Email Address"
value={this.state.email}
onChange={e => this.onChange(e)}
name="email"
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
name="password"
value={this.state.password}
onChange={e => this.onChange(e)}
minLength="6"
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Confirm Password"
name="password2"
value={this.state.password2}
onChange={e => this.onChange(e)}
minLength="6"
/>
</div>
<div className="form-group">
<input
type="file"
name="image"
onChange={e => this.onChangeImage(e)}
minLength="6"
/>
</div>

<input type="submit" className="btn btn-primary" value="Register" />
</form>
<p className="my-1">
Already have an account? <Link to="login">Sign In</Link>
</p>
{this.Alert()}
</div>
);
}
}

export default Register;

这是我的 Nodejs 代码......

const User = require("../../models/User");
const gravatar = require("gravatar");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const config = require("config");
const { check, validationResult } = require("express-validator");
const path = require('path');


const addUser = app => {
app.post(
"/api/addUser",
[
check("name", "Name is Required")
.not()
.isEmpty(),
check("email", "Please Enter a Valid Email").isEmail(),
check(
"password",
"Please Enter a Password with 6 or more charecters"
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}

try {
// if user exists send a error
const { name, email, password } = req.body;
const { image } = req.files;

console.log(req.body);

let user = await User.findOne({ email });
if (user) {
return res
.status(400)
.json({ errors: [{ msg: "User Already Exists" }] });
}
// get user avatar
const avatar = gravatar.url(email, {
s: "200",
r: "pg",
d: "mm"
});
await image.mv(path.resolve(__dirname,
'../public/images/Profile_Images', image.name));
user = new User({
name,
email,
password,
avatar,
image
});
console.log(image.name);
user.image = image.name;
// ecrypt the password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);

await user.save();

// return jsonweb token
const payload = {
user: {
id: user.id
}
};

jwt.sign(
payload,
config.get("jwtSecret"),
{ expiresIn: 36000 },
(err, token)=>{
if(err) throw err;
res.json({ token });
}
);
} catch (err) {
console.error(err.message);
res.status(500).send("Server Error");
}
}
);
};

module.exports = addUser;

我该如何解决这个问题?在我的用户模型中,图像是可选的,但姓名、电子邮件和
其他字段为必填

最佳答案

仅从上面的代码来看,您没有正确解析传入的请求,因为一旦将图像添加到表单数据中,它就会变成multipart/form-data。你需要像 multer 这样的东西为了它的工作。然后您就可以访问字段和图像。

关于node.js - 上传带有标题的图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57254248/

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