JAVASCRIPT
Client-Side Secure File Upload to AWS S3 with Pre-signed URL
Learn how to securely upload files directly from the browser to AWS S3 using pre-signed URLs, enhancing performance and offloading server resources.
async function getPresignedUrl(fileName, fileType) {
// In a real application, this would be an API call to your backend
// which generates and returns the pre-signed URL from AWS SDK.
const response = await fetch('/api/get-s3-presigned-url', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ fileName, fileType }),
});
if (!response.ok) {
throw new Error('Failed to get pre-signed URL');
}
const data = await response.json();
return data.url; // The pre-signed URL
}
async function uploadFileToS3(file) {
try {
const presignedUrl = await getPresignedUrl(file.name, file.type);
const uploadResponse = await fetch(presignedUrl, {
method: 'PUT', // or POST depending on how the URL was generated
headers: {
'Content-Type': file.type, // IMPORTANT: Must match the content-type signed
},
body: file, // The actual file object
});
if (!uploadResponse.ok) {
throw new Error(`S3 upload failed: ${uploadResponse.statusText}`);
}
console.log('File uploaded successfully to S3!');
// The S3 object URL might be returned by your backend after it confirms the upload
// or can be constructed if you know the bucket and key.
} catch (error) {
console.error('Error uploading file:', error);
}
}
// Example usage (e.g., attach to a file input change event)
document.getElementById('fileInput').addEventListener('change', async (event) => {
const file = event.target.files[0];
if (file) {
await uploadFileToS3(file);
}
});
How it works: This snippet demonstrates client-side file uploads directly to AWS S3 using a pre-signed URL. First, the client requests a secure, temporary pre-signed URL from a backend API, which specifies permissions and expiration. Then, the client uses this URL to send the file directly to S3. This approach offloads file transfer from the application server, improves scalability, and enhances security by limiting direct S3 access.