How can I design an upload process that only uploads specific files to an S3 bucket?

85    Asked by DanielBAKER in Salesforce , Asked on Feb 13, 2024

 I am currently working on a specific project in which users can upload files to an S3 bucket. However, I want to ensure that only specific types of files should be allowed, like images and PDFs. How can I design the upload process so that I can validate the files before the process of uploading them to the S3 bucket? 

Answered by Daniel Cameron

 In the context of AWS, you can ensure that only specific files should be allowed for uploading to an S3 bucket by implementing server-side validation before the files are uploaded. Here are the steps given of how you can do it in a typical web-based application by using Node.js and the AWS SDK:

Client side

You can try to implement basic file validation on the client side by using JavaScript so that you can prevent users from selecting unsupported file types. This would help you in improving the experience of users and reduce unnecessary requests to the server:-

// Client-side file type validation example
Const fileInput = document.getElementById(‘fileInput’);
fileInput.addEventListener(‘change’, (event) => {
  const file = event.target.files[0];
  const allowedTypes = [‘image/jpeg’, ‘image/png’, ‘application/pdf’];
  if (!allowedTypes.includes(file.type)) {
    alert(‘Unsupported file type. Please select an image (JPEG/PNG) or PDF file.’);
    event.target.value = ‘’; // Clear the file input
  }
});
Server side
You can also implement server-side validation so that you can double-check file types and even prevent any malicious uploads.
Const AWS = require(‘aws-sdk’);
Const multer = require(‘multer’);
Const multerS3 = require(‘multer-s3’);
Const s3 = new AWS.S3({
  accessKeyId: ‘YOUR_ACCESS_KEY_ID’,
  secretAccessKey: ‘YOUR_SECRET_ACCESS_KEY’,
  region: ‘YOUR_S3_REGION’
});
Const upload = multer({
  Storage: multerS3({
    S3: s3,
    Bucket: ‘YOUR_BUCKET_NAME’,
    Acl: ‘public-read’, // Set ACL for uploaded files
    contentType: multerS3.AUTO_CONTENT_TYPE,
    key: function(req, file, cb) {
      cb(null, Date.now() + ‘-‘ + file.originalname);
    }
  }),
  fileFilter: function(req, file, cb) {
    const allowedTypes = [‘image/jpeg’, ‘image/png’, ‘application/pdf’];
    if (allowedTypes.includes(file.mimetype)) {
      cb(null, true);
    } else {
      Cb(new Error(‘Unsupported file type. Please upload an image (JPEG/PNG) or PDF file.’));
    }
  }
});
// Example route for file upload
App.post(‘/upload’, upload.single(‘file’), (req, res) => {
  Res.json({ message: ‘File uploaded successfully!’ });
});


Your Answer

Interviews

Parent Categories