Skip to content

Instantly share code, notes, and snippets.

@jorke
Last active October 24, 2024 23:32
Show Gist options
  • Save jorke/b68b611c1b75086158935df2499396a7 to your computer and use it in GitHub Desktop.
Save jorke/b68b611c1b75086158935df2499396a7 to your computer and use it in GitHub Desktop.
s3 presigned post example with content-type - NOTE field.
import fs from 'node:fs';
import {
S3Client,
PutObjectCommand
} from "@aws-sdk/client-s3";
import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
import FormData from 'form-data';
const client = new S3Client({ region: "ap-southeast-2" });
const Bucket = "cv-edge";
const Key = "hi.png";
let file = null;
try {
file = fs.readFileSync('hi.png');
} catch (err) {
console.error(err);
}
const size = new Blob([file]).size
console.log(size)
const Conditions = [
["starts-with", "$key", Key],
['content-length-range', 0, size],
['eq', '$Content-Type', 'image/png']
];
const { url, fields } = await createPresignedPost(client, {
Bucket,
Key,
Conditions,
Fields: {
'Content-Type': 'image/png',
success_action_status: '201'
},
Expires: 3600, //Seconds before the presigned post expires. 3600 by default.
});
console.log(url, fields);
const form = new FormData();
Object.entries(fields).forEach(([field, value]) => {
form.append(field, value);
});
form.append("file", file, {
filename:'hi.png',
contentType: "image/png"
});
form.submit(url, (err, res) => {
if (err) throw err;
if (res.statusCode !== 200) {
console.log(res.statusCode, res.statusMessage)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment