JAVASCRIPT

Secure Client-Side File Upload with Pre-signed URLs

Enable secure and efficient direct file uploads from the browser to cloud storage (e.g., AWS S3) using temporary pre-signed URLs, offloading your backend.

async function uploadFileToPresignedUrl(file, presignedUrl) {
  try {
    const response = await fetch(presignedUrl, {
      method: 'PUT',
      headers: {
        'Content-Type': file.type,
      },
      body: file,
    });

    if (!response.ok) {
      throw new Error(`Failed to upload file: ${response.statusText}`);
    }
    console.log('File uploaded successfully!');
    return response;
  } catch (error) {
    console.error('Error uploading file:', error);
    throw error;
  }
}

// Example workflow:
// 1. Client requests a pre-signed URL from your backend for a specific file name/type.
// 2. Backend generates and returns the pre-signed URL (e.g., from AWS S3 SDK).
// 3. Client uses the pre-signed URL to directly upload the file to cloud storage.

// async function handleFileUpload(event) {
//   const file = event.target.files[0];
//   if (!file) return;

//   try {
//     // Replace with your actual backend endpoint to get a presigned URL
//     const presignedUrlResponse = await fetch('/api/get-presigned-url', {
//       method: 'POST',
//       headers: { 'Content-Type': 'application/json' },
//       body: JSON.stringify({ filename: file.name, filetype: file.type }),
//     });
//     const { presignedUrl } = await presignedUrlResponse.json();

//     await uploadFileToPresignedUrl(file, presignedUrl);
//     alert('Upload complete!');
//   } catch (error) {
//     alert(`Upload failed: ${error.message}`);
//   }
// }

// <input type="file" onchange="handleFileUpload(event)">
How it works: This snippet demonstrates how to perform a secure client-side file upload directly to cloud storage using a pre-signed URL. The browser first requests a temporary, signed URL from your backend for a specific file. Then, it uses this URL to `PUT` the file directly to the cloud storage provider (e.g., S3), bypassing your server for the actual file transfer. This improves performance, reduces server load, and enhances security by limiting direct access to storage buckets.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs