

















1. npm install sdk
npm install @aws-sdk/client-s3
npm install @aws-sdk/s3-request-presigner
2. 写一个产生put object的pre put url,比如叫这个文件名:genurl.js
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
const { getSignedUrl } = require("@aws-sdk/s3-request-presigner");
const s3Client = new S3Client({
region: "us-east-1", // region
credentials: {
accessKeyId: "xxxx", // Access Key ID
secretAccessKey: "xxxx", // Secret Access Key
}
});
const putObjectCommand = new PutObjectCommand({
Bucket: "test",
Key: "20250211165425.png"
});
async function gen() {
const url = await getSignedUrl(s3Client, putObjectCommand, { expiresIn: 3600 });
console.log(url);
}
gen();
3. cmd中输入:node genurl.js,得到一个pre put url
4. 写一个upload.html
<html><body>
<input type="file" id="fileInput" />
<button id="uploadButton">Upload</button>
<script>
document.getElementById('uploadButton').addEventListener('click', async function() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
console.log(file.type);
if (!file) {
alert('Please select a file!');return;
}
const preSignedUrl = 'https://test.s3.us-east-1.amazonaws.com/*****&x-id=PutObject';
try {
const response = await fetch(preSignedUrl, {
method: 'PUT',
body: file
});
if (response.ok) {
alert('successfully!');
} else {
alert('failed!');
}
} catch (error) {
console.error('Error:', error);
}
});
</script>
</body></html>
选一个文件上传就ok了
其他注意事项:
1)s3 上看到的bucket arn长这样
arn:aws:s3:::test
取最后一个test就行了,这里花了好长时间,被AI骗了
2)AI会给你v2的解决方案,别信它的,现在需要npm aws-sdk v3,也就是带@的
3)配置S3的CORS策略通常涉及在S3桶的配置中添加一个CORS规则,该规则指定了哪些源(origins)被允许访问桶中的资源,以及允许哪些HTTP方法和头部(headers)
配置S3 CORS的详细步骤:
附json:
[ { "AllowedHeaders": [ "Authorization", "Content-Type", "X-Amz-Date", "X-Amz-Security-Token" ], "AllowedMethods": [ "GET", "PUT", "POST", "DELETE" ], "AllowedOrigins": [ "http://localhost", "https://localhost", "http://127.0.0.1", "https://127.0.0.1" ], "ExposeHeaders": [ "x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2" ], "MaxAgeSeconds": 3600 } ]
AI又骗我用xml
xxxx这个不能用!
<CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> </CORSRule> </CORSConfiguration>
xxxx这个不能用!
4)AI在写产生pre put url的代码时,用了GetObjectCommand,又害我想了好久
const { S3Client, GetObjectCommand} = require("@aws-sdk/client-s3");
正确的应该是这样:
const { S3Client, PutObjectCommand } = require("@aws-sdk/client-s3");
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。