reactjs - 使用 reactjs 和 mongodb 上传图片
问题描述
我正在尝试在 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。我错过了什么? 谢谢。
解决方案
您可以使用它来上传图像。使用async/await
.
async uploadImage(image) {
const form = new FormData();
form.append('file', image);
form.append('upload_preset', 'g5ziunzg');
const res = await Axios.post('YOUR_CLOUDINARY_URL', form)
console.log(res)
return res.data;
}
这将返回一个对象secure_url
,您可以将其存储在您的 mongo 数据库中。我假设你有这个任务的后端 API。
在您的 formSubmit 函数中,您可以首先调用此函数并接收 this secure_url
。
请注意,我在axios
这里使用。这个例子可以很容易地翻译成使用fetch
.
推荐阅读
- apache-kafka - 在具有不同类型的 JSON 值主题上定义 KSQL STRUCT
- symfony - 输入和输出类的 Symfony 依赖注入
- scala - 使用 Spark xgboost4j 提前停止时如何获取 iter?
- java - FileProvider 无法解析 XML
- java - Apache lucene:对数字和德语变音符号进行排序
- sql - Laravel 将单独的记录合并为一个记录
- spring - 内存中的spring boot activemq
- c# - 是否可以使用 async/await 向 RabbitMQ 发布消息?
- ios - 框架类是否应该导入伞头
- android - 第二页的导航按钮出现在主页上