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

如何解决Cloudinary上传时的ERR_SOCKET_CONNECTION_TIMEOUT错误?

Cloudinary上传文件出现Socket连接超时的解决办法

问题场景

使用Multer作为中间件处理本地磁盘文件,自定义uploadOnCloudinary函数上传至Cloudinary时,触发ERR_SOCKET_CONNECTION_TIMEOUT错误,更换多个Node稳定版本后问题仍未解决。

自定义上传函数代码

const uploadOnCloudinary = async (localFilePath) => {
    try {
        if (!localFilePath) return null
        //upload the file on cloudinary
        const response = await cloudinary.uploader.upload(localFilePath,{
            resource_type: "auto"
        })
        //file has been uploaded successfull
        console.log("file is uploaded on cloudinary ", response.url);
        fs.unlinkSync(localFilePath)
        return response;
    } catch (error) {
        console.error("error uploading",error);
        fs.unlinkSync(localFilePath) // remove the locally saved temporary file as the upload operation got failed
        return null;
    }
}

报错信息

error uploading {
  error: Error [ERR_SOCKET_CONNECTION_TIMEOUT]: Socket connection timeout
      at new NodeError (node:internal/errors:399:5)
      at internalConnectMultiple (node:net:1099:20)
      at Timeout.internalConnectMultipleTimeout (node:net:1638:3)
      at listOnTimeout (node:internal/timers:575:11)
      at process.processTimers (node:internal/timers:514:7) {
    code: 'ERR_SOCKET_CONNECTION_TIMEOUT'
  }
}

解决步骤

  • 检查网络与Cloudinary连通性

    • 测试本地/服务器能否访问Cloudinary上传接口,执行命令:curl -v https://api.cloudinary.com/v1_1/<你的云名>/image/upload,确认返回正常HTTP响应
    • 服务器环境下,检查防火墙、安全组是否允许443端口的出站请求
    • 国内网络环境可尝试切换至Cloudinary国内节点,将上传域名改为https://api.cloudinary.com.cn
  • 调整Cloudinary客户端超时配置

    • 初始化Cloudinary时全局设置超时:
      cloudinary.config({
        cloud_name: '你的云名',
        api_key: '你的API密钥',
        api_secret: '你的API密钥',
        timeout: 60000 // 设置60秒超时,覆盖默认值
      });
      
    • 或在单个上传请求中单独指定超时:
      const response = await cloudinary.uploader.upload(localFilePath, {
        resource_type: "auto",
        timeout: 60000
      })
      
  • 优化本地文件清理逻辑

    • 在删除临时文件前先判断文件是否存在,避免触发额外错误:
      if (fs.existsSync(localFilePath)) {
        fs.unlinkSync(localFilePath);
      }
      
    • 考虑改用异步删除方法避免阻塞主线程:
      // 替换原有的fs.unlinkSync为以下代码
      await fs.promises.unlink(localFilePath);
      
  • Node版本适配建议

    • 推荐使用Node.js 18.x或20.x LTS版本,这两个版本的网络模块稳定性强,且Cloudinary官方SDK对其支持完善
    • 避免使用Node.js 14.x及以下版本,旧版本网络API存在已知的连接超时相关问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 03:18:18