Search code examples
javascriptpostgresqlreact-reduxloopbackjsfile-type

Explicitly set Javascript files mimetype



As I am pretty new to React, need help, please.

I have encountered a use case where the client is uploading a javascript file in the project but upload fails because different browsers see the same file in a different way (in terms of file type).

As per project guidelines, only 'application/javascript' files are allowed to get saved in the database. but when a user uploads a file from chrome it gives as 'text/javascript' and uploads fail.

now the client wants us to update the mime-type of javascript files, for example, if 'text/javascript' comes to the server rewrite the mime-type to 'application/javascript' and save the file.

is it even possible to change a JS file mime-type ?

if Yes, any help is really appreciated.
What is the ideal way to solve this issue.

JS file, being supported in Database.

[
  {
    "id": "aac491d22bcbb4a95deed88b738c1edc",
    "mimeType": "application/javascript",
    "extensions": [
      "js"
    ],
    "mediaTypeGroupId": "21f64da1e5792c8295b964d159a14491",
    "created": "2021-11-15T06:31:52.237Z",
    "updated": "2021-11-15T06:31:52.237Z",
    "self": "/mediatypes/aac491d22bcbb4a95deed88b738c1edc"
  }
]

clients Wants us to do like this (just sample code, forgive idea)

if (file.files[0].type === "text/javascript") {
    const newType = file.files[0].type;
    newType = "application/javascript";
    console.log("yes", file.files[0].type);
  }

PS: Tech-Stack used is REACT, REDUX, LOOPBACK, POSTGRES.
Thank you.


Solution

  • You can re-create the File object and override the type using the method below.

    new File([file], file.name, {type: "application/javascript"});
    

    For your example, you can use it like this, you'll see the only change will be the type.

    if (file.files[i].type === "text/javascript") {
        file.files[i] = new File(file.files[i], file.files[i].name, {
            type: "application/javascript",
        });
    }