【发布时间】:2019-12-31 21:37:16
【问题描述】:
我正在尝试在 reactjs 中制作一个图片上传器,这要归功于一个表单。 我在 mongodb 中创建了一个 api(感谢 express、mongoose 等),我正在尝试使用它来上传图片。
实际上,我想将图像文件发送到云端(使用 Cloudinary),并获取 url。
这是我的形式和方法:
class Header extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
data: [],
uploading: false,
image: [],
apiKey: 'xxx'
};
}
onChangeImage = e => {
this.setState({[e.target.name]: Array.from(e.target.files)});
};
sendImage = files => {
const formData = new FormData();
files.forEach((file, i) => {
formData.append(i, file)
});
fetch('http://localhost:3000/image-upload', {
method: 'POST',
headers : new Headers({
'Content-Type' : 'application/x-www-form-urlencoded',
'x-access-token' : this.state.apiKey
}),
body: formData
})
.then(res => res.json())
.then(image => {
this.setState({
uploading: false,
image
});
return true;
});
return false;
};
handleSubmit = (event) => {
event.preventDefault();
const { image } = this.state;
this.sendImage(image);
};
render() {
return(
<form onSubmit={this.handleSubmit} className="formAdd">
<input type='file' id="image" name="image" onChange={this.onChangeImage} />
<button className="contact-form-btn">
Send<i className="fa fa-long-arrow-right" aria-hidden="true"></i>
</button>
</form>
)
}
关于我的 API 控制器:
const cloudinary = require('cloudinary');
module.exports = {
create: function(req, res) {
cloudinary.config({
cloud_name: 'xxxx',
api_key: 'xxxxx',
api_secret: 'xxxxx'
});
const path = Object.values(Object.values(req.body.files)[0])[0].path;
cloudinary.uploader.upload(path)
.then(image => res.json([image]));
},
};
我得到的错误代码是 500 'TypeError: Cannot convert undefined or null to object'。 确实,它没有找到 Object.values(Object.values(req.body.files)[0])[0].path。 我错过了什么? 谢谢。
【问题讨论】:
标签: reactjs mongodb forms mongoose