You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS与Node JS项目中上传后如何立即获取Cloudinary图片URL

解决方案

最优实现逻辑为:后端在上传成功的响应体中直接返回Cloudinary生成的图片URL,前端接收响应后将URL存入React状态即可,无需额外发起查询请求,步骤如下:

1. 修改后端 /api/upload 接口

Cloudinary上传成功后返回的uploadedResponse对象中secure_url字段就是你需要的HTTPS格式访问URL,修改上传接口的返回逻辑,把该字段返回给前端:

app.post('/api/upload', async (req, res) => {
    try {
        const fileStr = req.body.data;
        const uploadedResponse = await cloudinary.uploader.upload(fileStr, {upload_preset: 'dev_setups'})
        // 新增返回图片URL
        res.json({
            msg: "Success",
            url: uploadedResponse.secure_url
        })
    } catch (error){
        console.error(error)
        res.status(500).json({err: 'Something went wrong'})
    }
})

2. 调整前端React代码

首先新增状态存储Cloudinary返回的图片URL,然后修改uploadImage函数接收后端响应,将URL存入状态:

2.1 新增状态

在现有状态声明区域添加:

const [uploadedCloudinaryUrl, setUploadedCloudinaryUrl] = useState('')

2.2 修改uploadImage函数

const uploadImage = async (base64EncodedImage) => {
    console.log(base64EncodedImage)
    try {
        const res = await fetch('/api/upload', {
            method: 'POST',
            body: JSON.stringify({data: base64EncodedImage}),
            headers: {'Content-type': 'application/json'}
        })
        const data = await res.json()
        // 上传成功后将URL存入状态
        if (res.ok) {
            setUploadedCloudinaryUrl(data.url)
            // 后续如果需要随帖子一起提交,直接使用uploadedCloudinaryUrl变量即可
        }
    } catch (error) {
        console.error(error)
    }
}

如果需要在提交帖子的时候同时携带图片URL,直接在handleSubmit方法的makePostAction参数中加入imageUrl: uploadedCloudinaryUrl字段即可。

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:57:04