React 里用 presigned URL 上传文件到 S3 为啥总报 403?
我用后端生成的 presigned URL 在前端直接 PUT 上传文件,但每次都是 403 Forbidden。CORS 和权限策略都检查过了,应该没问题啊?
下面是我用 React 写的上传逻辑,file 是用户选的文件:
const uploadToS3 = async (file, presignedUrl) => {
try {
const response = await fetch(presignedUrl, {
method: 'PUT',
headers: {
'Content-Type': file.type,
},
body: file,
});
console.log(response);
} catch (err) {
console.error('Upload failed:', err);
}
};
奇怪的是,同样的 URL 用 curl 能传成功,但浏览器里就不行,是不是少了什么 header?
Content-MD5和Authorization头,和 presigned URL 的签名冲突了,去掉自定义 header,只传Content-Type就行: