我正在尝试使用<input type="file" />
上传图像并上传该图像以通过节点路由进行云化。问题是文件永远不会到达后端。当我尝试console.log(req.file)
时,我会感到“不确定”。
前端:
class AddPlayer extends Component {
constructor(props) {
super(props);
this.state = {
avatar: profilePicPlaceholder,
avatarFile: "",
name: "",
age: "",
apodo: "",
captain: false,
description: "",
atributes: "",
facebook: "",
instagram: "",
twitter: "",
youtube: "",
errors: {},
displaySocialInputs: false
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.onCheck = this.onCheck.bind(this);
this.onImageChange = this.onImageChange.bind(this);
}
componentWillReceiveProps(nextProps) {
if (nextProps.errors) {
this.setState({ errors: nextProps.errors });
}
}
onSubmit(e) {
e.preventDefault();
const playerData = {
playerAvatar: this.state.avatarFile,
name: this.state.name,
age: this.state.age,
apodo: this.state.apodo,
captain: this.state.captain,
description: this.state.description,
atributes: this.state.atributes,
facebook: this.state.facebook,
instagram: this.state.instagram,
twitter: this.state.twitter,
youtube: this.state.youtube
};
this.props.addPlayer(playerData, this.props.history);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onImageChange(event) {
//this is to see the picture in the page.
if (event.target.files && event.target.files[0]) {
this.setState({ avatarFile: event.target.files[0] });
let reader = new FileReader();
reader.onload = e => {
this.setState({ avatar: e.target.result });
};
reader.readAsDataURL(event.target.files[0]);
}
}
render() {
<form
onSubmit={this.onSubmit}
method="post"
encType="multipart/form-data"
>
<div className="text-center mb-3">
<input
type="file"
name="file"
id="file"
accept="image/*"
className="inputfile"
onChange={this.onImageChange}
/>
<label htmlFor="file" className="btn btn-primary">
Elegir foto
</label>
</div>
</form>
}
}
AddPlayer.propTypes = {
addPlayer: PropTypes.func.isRequired,
profile: PropTypes.object.isRequired,
errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
profile: state.profile,
errors: state.errors
});
export default connect(
mapStateToProps,
{ addPlayer }
)(withRouter(AddPlayer));
这是带有将图像保存在cloudinary中的路由的文件:
const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const passport = require("passport");
const fs = require("fs");
const multer = require("multer");
const cloudinary = require("cloudinary");
const cloudinaryStorage = require("multer-storage-cloudinary");
const cloudname = require("../../config/keys").cloudname;
const API_KEY = require("../../config/keys").API_KEY;
const API_SECRET = require("../../config/keys").API_SECRET;
cloudinary.config({
cloud_name: cloudname,
api_key: API_KEY,
api_secret: API_SECRET
});
const storage = cloudinaryStorage({
cloudinary: cloudinary,
folder: "pics/",
allowedFormats: ["jpg", "png"],
transformation: [{ width: 500, height: 500, crop: "limit" }]
});
const parser = multer({ storage: storage });
router.post(
"/player",
[passport.authenticate("jwt", { session: false }), parser.single("file")],
(req, res) => {
console.log(req.file);
}
);
和server.js:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const matches = require("./routes/api/matches");
const app = express();
//body-parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//db config
const db = require("./config/keys").mongoURI;
//connect to mongoose
mongoose
.connect(
db,
{ useNewUrlParser: true }
)
.then(() => console.log("MongoDB connected"))
.catch(err => console.log(err));
//Passport middleware
app.use(passport.initialize());
//Passport config
require("./config/passport")(passport);
app.use("/api/profile", profile);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`server running on port ${port}`));
我发送的所有数据都到达了后端,我可以使用req.body来访问它,但是req.file中什么都没有。
我希望有人能帮助我。预先感谢。