Skip to content

Instantly share code, notes, and snippets.

@tschoffelen
Last active July 25, 2020 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tschoffelen/0ac254592adb3a98b2b9211c4b8d53dc to your computer and use it in GitHub Desktop.
Save tschoffelen/0ac254592adb3a98b2b9211c4b8d53dc to your computer and use it in GitHub Desktop.
Example of uploading files to S3 via signed URLs.
// Frontend uploader example
// URL for your lambda function
const backendUrl = "https://xxxxxx.execute-api.eu-west-1.amazonaws.com/production/create-upload-url"
// Accepts a File object here, for example from
// a <input type="file"> or drag and drop action
const uploadFile = (file) => {
const filename = encodeURIComponent(file.name)
const type = encodeURIComponent(file.type)
// First get a signed URL based on filename and mime type
// from our lambda function
console.log("Getting signed upload URL...")
fetch(`${backendUrl}?filename=${filename}&contentType=${type}`)
.then(res => res.json())
.then(({ key, url }) => {
console.log(`Signed URL: ${url}`)
console.log(`Uploading ${file.name}...`)
// If you're uploading large files, you might want to swap
// out fetch here with something more robust that reports
// upload progress and supports multipart uploads
fetch(url, { method: "PUT", body: file })
.then(() => {
console.log(`Finished uploading to: ${key}`)
})
})
}
// Code for your lambda function
const AWS = require("aws-sdk")
const s3 = new AWS.S3({ useAccelerateEndpoint: true })
exports.handler = async ({ queryStringParameters }) => {
const { filename, contentType } = queryStringParameters
const randomString = Math.random().toString(36).substring(2, 5)
const key = `unprocessed/${randomString}-${filename}`
const url = s3.getSignedUrl("putObject", {
Bucket: process.env.BOX_BUCKET,
Key: key,
Expires: 600,
ContentType: contentType,
ACL: "public-read"
})
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
body: JSON.stringify({
key,
url
})
}
}
# Your function definition in serverless.yml
functions:
create-upload-url:
handler: functions/create-upload-url.handler
memorySize: 128
timeout: 30
events:
- http:
path: /create-upload-url
method: get
cors: true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment