【问题标题】:Upload an image with reactjs and mongodb使用 reactjs 和 mongodb 上传图片
【发布时间】: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


    【解决方案1】:

    您不需要使用Object.value,因为req.body.files 是一个数组,您需要在访问之前检查它的长度。试试看:

    const [file] = req.body.files
    
    if (file) {
      // your logic here
    }
    
    

    【讨论】:

    • 感谢您的反应!通过直接请求 Cloudinary API 解决!
    【解决方案2】:

    您可以使用它来上传图片。使用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 函数中,您可以先调用此函数并接收此secure_url

    请注意,我在这里使用的是axios。这个例子可以很容易地翻译成fetch

    【讨论】:

    • 干得好!太感谢了!我不知道为什么我使用我的 API 在服务器上上传。你的代码工作正常!
    猜你喜欢
    • 2022-07-17
    • 2017-08-03
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2021-05-09
    • 2021-07-07
    相关资源
    最近更新 更多