How to restrict some file types from uploading in google-cloud-storage, and also determine if the file is a document or an image?

Viewed 18

I am using the code as given in the firebase storage documentation to upload files to my project.

Here is the code:

var metadata = {
  contentType: 'image/jpeg'
};

var uploadTask = storageRef.child('images/' + file.name).put(file, metadata);

uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, 
  (snapshot) => {
  
    var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
    console.log('Upload is ' + progress + '% done');
    switch (snapshot.state) {
      case firebase.storage.TaskState.PAUSED: 
        console.log('Upload is paused');
        break;
      case firebase.storage.TaskState.RUNNING: 
        console.log('Upload is running');
        break;
    }
  }, 
  (error) => {
    switch (error.code) {
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the upload
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect error.serverResponse
        break;
    }
  }, 
  () => {
    uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
      console.log('File available at', downloadURL);
    });
  }
);

I want to add some functionalities. The first functionality is that I could determine whether the file being uploaded is a document or a photo. The second functionality is that I will only allow pdf and jpeg format files to be uploaded.

In order to achieve these functionalities does firebase storage provides any function or do I need to manually determine the file type from the file name by using the split function?

1 Answers

Cloud Storage does not offer content type restriction enforcement except for Signed URLs which can enforce the HTTP content-type header.

Do not use the filename to determine file types. There are good libraries that offer more reliable content type detection. Detecting PDF and JPEG can be easily performed by reading the first few bytes of the file. That is not a guarantee as random data can also have the required byte values in key data locations.

Related