Using file types in Vue 3: a beginner's guide

In order to use file-type to determine not only the extension but also ensure the headers are correct I would need to use one of the methods listed on their GitHub page. In version 19.0.0 it says fileFromFileType doesn't have such an export and in 16.5.4 it says it's not a valid function.

This is the page I need it on, but you can also check out the repo here

<template>
  <div style="font: 13px Verdana; background: #eee; color: #333; margin: 2px; padding: 20px;">
    <h1>Upload een foto</h1>

    <div id="filelist">Your browser doesn't have Flash, Silverlight or HTML5 support.</div>
    <br />

    <div id="container">
      <a id="pickfiles" href="javascript:;">[Select files]</a> 
      <a id="uploadfiles" href="javascript:;" @click="checkValidFile">[Upload files]</a>
    </div>
    <br />

    <pre id="console">{{ errorMessage }}</pre>
  </div>
</template>

<script>
import plupload from 'plupload';
import * as fileType from 'file-type';
export default {
  data() {
    return {
      uploader: null,
      errorMessage: ''
    }
  },
  mounted() {
    this.uploader = new plupload.Uploader({
      runtimes : 'html5,flash,silverlight,html4',
      browse_button : 'pickfiles',
      container: document.getElementById('container'),
      url : 'https://localhost:7104/api/PlUpload/File', 
      flash_swf_url : '../js/Moxie.swf',
      silverlight_xap_url : '../js/Moxie.xap',
      chunk_size:'5mb',
      max_retries: 100,

      filters : {
        max_file_size : '5gb',
        mime_types: [
          {title : "Image files", extensions : "jpg,jpeg,gif,png"},
          {title : "Movies", extensions : "mp4"}
        ]
      },

      init: {
      PostInit: () => {
        document.getElementById('filelist').innerHTML = '';
      },

      FilesAdded: (up, files) => {
        files.forEach(file => {
          document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';
        });
      },

      UploadProgress: (up, file) => {
        document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
        if (file.percent === 100) {
          this.errorMessage = '';
        }
      },

      ChunkUploaded: (up, file) => {
        const delayBetweenChunks = 15; 
        setTimeout(() => {
          up.trigger('UploadProgress', file);
          up.trigger('BeforeUploadChunk', file);
        }, delayBetweenChunks);
      },

      Error: (up, err) => {
        if (err.code === plupload.HTTP_ERROR && err.status === 0) {
          this.errorMessage = 'Netwerkfout, verbind opnieuw met uw internet zodat de upload weer start.';
        } else {
          this.errorMessage = 'Error';
        }
      },  
    },
      
    });

    this.uploader.init();
  },
  methods: {
    selectFiles() {
      this.uploader.start();
    },

    generateUniqueIdentifier() {
      const timestamp = Date.now();
      const randomString = Math.random().toString(36).substring(2, 15);
      return `${timestamp}-${randomString}`;
    },

    uploadFiles() {
      this.uploader.start();
    },

    async checkValidFile() {
      if (!this.uploader.files.length) {
        console.error('Geen bestand geselecteerd.');
        return;
      }

      for(let i = 0; i< this.uploader.files.length; i++){
        let file = this.uploader.files[i];
        console.log(await fileType.fileTypeFromFile(file));
      }

    },
    
  }
}
</script>

Answer №1

It appears that the fileTypeFromFile function is not accessible in a browser environment, but rather exclusively in a node environment.

Since you are utilizing the library in a browser setting, I suggest using alternative functions such as fileTypeFromStream, fileTypeFromBuffer, or fileTypeFromBlob

For instance:

console.log(await fileType.fileTypeFromStream(file));

and

console.log(await fileType.fileTypeFromBuffer(file));

You can explore all available functions exported by the file-type package for browser environments here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transfer the elements from one array list to another array list

I need to duplicate the array list below $scope.medicinelist = [ {medicine: 'AMLOPRES 5MG TABLET'}, {medicine: 'ARGIPREG SACHET'}, {medicine: 'ALCIPRO 500MG TABLET'} , {medicine: 'PROLOMET AM 50MG TABLET'}, {medic ...

Utilizing a checkbox within a select dropdown component in Vue

Has anyone come across a checkbox dropdown feature in Vue? I have been searching online but couldn't find any examples or resources related to this. If someone has a working skeleton for it, please share! ...

Having trouble downloading a PDF file on a local server with React and the anchor tag element

Having trouble downloading a pdf file from my react app to my Desktop. I've reached out for help with the details How to download pdf file with React. Received an answer, but still struggling to implement it. If anyone new could provide insight, that ...

Show singular array element upon click

I need help with a specific task. When a button is clicked, I want to display a random item from an array. Each array item should only be displayed once. Currently, my code is set up as follows: When the button is clicked, a random array item is displ ...

Looking for a resolution? Ensure that actions are plain objects by employing custom middleware specifically designed for managing asynchronous actions

I'm attempting to replicate a MERN stack project named Emaily, but I've encountered an error Error: Actions must be plain objects. Use custom middleware for async actions. Here is the code for my Action: import axios from 'axios'; im ...

Unspecified locale with Next.js router

Despite extensive research and multiple attempts, I have not been able to find a solution to my problem. That's why I am reaching out for help again. Currently, I am working on a local project and I would like to implement Internationalized Routing f ...

Unlock the power of Angular JS to display dynamic content effortlessly

My experience with AngularJs is very limited. In one of my projects, I need to display dynamic content on a page that changes based on the database values retrieved via an HTTP GET request. Before implementing the entire functionality, I decided to test i ...

InvalidType Error: The roles provided are not in the correct format, it should be a Role, Snowflake, or an Array/Collection of Roles or Snowfl

Having trouble setting up multiple select menu options on Discord.js v14. I'd like to assign more than one role to a member when multiple options are chosen in the dropdown menu. However, I'm encountering this error message: TypeError [Invalid ...

What is the reason for the inability to input a null byte in a file when using ascii mode with node.js?

Below is the code snippet I have written: var fs = require('fs'); var fp = fs.openSync('binary.txt', "w"); var byte = '\0'; fs.writeSync(fp, byte, null, 'ascii'); However, upon execution, when I check the con ...

Having trouble getting Node.js to run Express.js and React.js simultaneously

My tech stack consists of reactjs for the frontend and expressjs for the backend API. I experimented with the following setup: { "name": "carweb", "version": "0.1.0", "private": true, "dependencies": { // list of dependencies }, "scripts ...

Accessing Jquery's $.get function is currently not possible

I am experiencing difficulty fetching the contents of a json.txt file located in the same directory as this markup. Additionally, there are no errors appearing in Firebug. <!DOCTYPE html> <html> <head> <script type="text/ja ...

Avoiding a jest compile error and executing the test efficiently

Here is my Vue.js code snippet: export default { name: 'App', components: { }, created() { let t = typeof t === 'undefined' ? {} : t; // ISSUE LINE } } The ISSUE LINE runs successfully in the browser without any errors an ...

Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function. var takeSword = function() { if (currentRoom.hasSword) { $("<p>You picked up a sword.</p&g ...

Ajax is able to fetch the URL without any issues, but the page is not being updated as expected. Instead,

I am currently working on implementing next/prev buttons using JavaScript, and have utilized a DynamicPage script for testing purposes. The only modification I made was to the beginning of the URL variable in pagenumber.js, although it essentially delivers ...

The counter variable does not function properly within a setInterval function

I have encountered an issue with my scroll-counter variable inside the setInterval function. It increments by 1 each time the setInterval function runs, which is supposed to happen 20 times before stopping. However, I noticed that the value of this variabl ...

Exploring the power of Node.js and EJS through the art of

Recently delving into the world of node.js, I encountered a puzzling issue with my EJS template. It seems that my for loop is not executing properly within the EJS template while attempting to create a basic todo app. Below is the structure of the project ...

A computer program designed to determine a series of numbers needed to complete a square grid

Given the numbers 1, 2, 3, 4, 5, 6, 7, 8, I am seeking to replace the x's in such a way that each side adds up to the number in the center. *-*---*-* |x| x |x| *-*---*-* |x| 12|x| *-*---*-* |x| x |x| *-*---*-* Initially, I have iterated over the num ...

Nonspecific _POST parameter error encountered while utilizing XMLHttpRequest()

I am currently experimenting with Ajax to add data into a database using the POST method. However, I am facing an issue where PHP is unable to recognize the post variables being sent. ajax: function createUser() { var _id=document.getElementById('ne ...

Is it possible to develop in React without using webpack, relying solely on Gulp instead?

Although I appreciate some aspects of Webpack, my enthusiasm for it wanes as the configuration files grow beyond 15 lines. It becomes overly cryptic, difficult to configure, and time-consuming. Therefore, I tend to reserve its use for just a couple of task ...

Tips on working with an array received from a PHP script through AJAX

I've been stuck with this issue for the past few hours and I'm hoping to find a solution here. What I'm attempting to do is something like the following: PHP: $errorIds = array(); if(error happens){ array_push($errorIds, $user['user ...