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

DigitalOcean存储大于5MB图片时返回格式错误的URL问题求助

DigitalOcean Spaces 上传大文件后URL格式错误的解决方法

问题场景

我使用DigitalOcean Spaces存储图片,之前搭配Firebase时一切正常。迁移至MongoDB与Node.js服务器后,上传大于5MB的图片时,返回的URL缺失https://前缀,且Bucket名称的位置也错误。

预期URL格式:

https://my-bucket.nyc3.digitaloceanspaces.com/folderName/image_picker_44B4654D-A164-41A8-B86E-4844B3699137-88682-00002E3606926DB8.jpg

实际得到的URL:

nyc3.digitaloceanspaces.com/my-bucket/folderName/image_picker_44B4654D-A164-41A8-B86E-4844B3699137-88682-00002E3606926DB8.jpg

我的代码片段:

const file = req.files.image;
const businessId = req.body.businessId;
const buffer = fs.readFileSync(req.files.image.filepath);
const spacesEndpoint = new aws.Endpoint('nyc3.digitaloceanspaces.com');
const s3 = new aws.S3({
  endpoint: spacesEndpoint,
  region: 'nyc3',
  credentials: {
    accessKeyId: 'uuuuuuuuuuuuuuuuuu',
    secretAccessKey: 'YYYYYYYYYYYYYY',
  },
});

s3.upload(
  {
    Bucket: 'dummy-spaces', // Add bucket name here
    ACL: 'public-read', // Specify whether anyone with link can access the file
    Key: `businessPhotosOfWork/${file.originalFilename}`, // Specify folder and file name
    Body: buffer,
  },
  {},
).send((err: AWSError | null, data: any) => {
  console.log(`${err}`);
  if (err) return res.status(500).send({ message: `${err}` });

  // Unlink file
  fs.unlinkSync(file.filepath);

  return successResponse(res, 'Operation Successful', { url: data.Location });
  // Return file url or other necessary details
});

问题原因

AWS SDK处理大文件上传(分片上传)时,默认使用路径式Bucket寻址,而DigitalOcean Spaces采用的是子域名式寻址,同时SDK未自动添加HTTPS前缀,导致生成的URL格式不符合预期。


解决方法

修改S3客户端配置,添加两个关键参数强制使用正确的URL格式:

const s3 = new aws.S3({
  endpoint: spacesEndpoint,
  region: 'nyc3',
  credentials: {
    accessKeyId: 'uuuuuuuuuuuuuuuuuu',
    secretAccessKey: 'YYYYYYYYYYYYYY',
  },
  s3ForcePathStyle: false, // 禁用路径式Bucket寻址,强制子域名格式
  signatureVersion: 'v4' // 确保签名规范与DigitalOcean匹配,自动生成HTTPS前缀
});

若上述配置后仍存在问题,可手动拼接标准URL替代data.Location:

// 替换原返回URL的代码
const correctUrl = `https://${data.Bucket}.${spacesEndpoint.hostname}/${data.Key}`;
return successResponse(res, 'Operation Successful', { url: correctUrl });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 08:25:20