首页 > 解决方案 > 使用 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。我错过了什么? 谢谢。

标签: reactjsmongodbformsmongoose

解决方案


您可以使用它来上传图像。使用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.


推荐阅读