What is the process for accessing the browse folder to upload a file?

I am using the vue-upload-component to handle file uploads. My requirement is to display the uploaded images and provide a button on each image to upload a new image. Since I found that this plugin does not have a method for changing an uploaded file, I am considering doing it manually. However, I am unsure about how to open a folder to choose files.

Can someone guide me on how to open a browse folder to select a new image?

</template>
<div>
 <file-upload
   :ref="uploaderName"
   v-model="files"
   :input-id="uploaderName"
   :extensions="formats"
   :drop="drop"
   :multiple="multiple"
   @input-filter="inputFilter"
   >
    Upload a file
 </file-upload>
 <span>or drag and drop</span>
</div>

<div
 v-show="files.length && !loading"
 class="flex"
>
 <img
   v-for="image in files"
   :key="image.id"
   :src="image.url"
   :style="[imageSize]"
   class="uploaded-image p-2 mr-2 border rounded border-gray-200"
  >
  <button @click.prevent='() => uploadNew(image)'>
    Upload new
  </button>
  <button @click.prevent='() => removeFile(image)'>
    Remove
  </button>
</div>
</template>

<script>
import FileUpload from 'vue-upload-component';

export default {
  name: 'UploadFileForm',
  components: {
    FileUpload,
  },
  props: {
    uploaderName: {
      type: String,
      required: true,
      default: '',
    },
    formats: {
      type: Array,
      default: () => ['.jpg', '.jpeg', '.svg', '.png', '.webp'],
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    drop: {
      type: Boolean,
      default: true,
    },
    imageWidth: {
      type: Number,
    },
    imageHeight: {
      type: Number,
    },
    value: {
      type: Array,
      default: () => {},
    },
  },
  data() {
    return {
      files: this.value || [],
      error: '',
      loading: false,
      hover: false,
      minImageWidth: 372,
      minImageHeight: 300,
    };
  },
methods: {
    removeFile(file) {
      this.$refs[this.uploaderName].remove(file);
    },
    uploadNew() {
      
    }
};
</script>

Answer №1

Various methods can be used to achieve this task. One effective approach is to create a designated area where users can either select a file for uploading or simply drag and drop the file.

<template>
  <div class="file-upload">
    <div
      class="text_field"
      @click="pickFile"
      @drop="uploadFile"
      @dragover.prevent
      @drop.prevent
    >
      <input
        id="file"
        ref="image"
        :accept="allowedFileTypes"
        style="display: none"
        type="file"
        @change="uploadFile"
      />
      <span v-if="fileUploading"> File uploading </span>
      <span v-else> Drag file here or click to upload </span>
    </div>
  </div>
</template>

Script

<script>
export default {
  name: "UploadFile",
  data() {
    return {
      fileUploading: false,
      allowedFileTypes: ".pdf, .jpg, .jpeg, .png, .doc, .docx, .xls, .xlsx, video/*, audio/*",
    };
  },
  methods: {
    pickFile() {
      this.$refs.image.click();
    },
    async uploadFile(e) {
      this.fileUploading = true;
      const files = e.target.files || e.dataTransfer.files;
      if (!files.length) {
        return;
      }
      const file = document.getElementById("file").files[0];
      /* Creating a form element so that it can be detected as req.files (in Node.js, for example) */
      const fileForm = new window.FormData();
      fileForm.append("file", file);
      /* Simulating uploading of files, we wait for two seconds */
      setTimeout(() => {
        this.fileUploading = false;
      }, 2000);
      /* Below, you can make a request to your backend to post the image */
      /* await axios.post('your_upload_file_url', fileForm)
        .then(res => res)
        .catch((error) => Promise.reject(error))
        */
    },
  },
};
</script>

You can also include some custom styles to enhance the user interface

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.file-upload {
  border: 1px dashed #007991FF;
  border-radius: 5px;
  height: 192px;
  cursor: pointer;
  text-align: center;
  vertical-align: middle;
  span {
    position: relative;
    top: 75px;
    padding: 20px;
    font-size: 14px;
    color: #cac8c8;
  }
}
</style>

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

Ways to choose a designated element without relying on ids or classes

I am looking to create an on-click function for each button, so I require a method to select each one individually without relying on IDs <div class="col"> <div> <b>Name:</b> <span ...

Using Typescript and Angular to efficiently filter an array of objects

I am dealing with an array of objects that contain a "category" attribute. My goal is to filter this array and retrieve only the objects with the "tech" category. An error message is being displayed stating that "filter" does not exist on type {} stocks- ...

Display a solo element from an array sent from Express to an EJS template, along with a "next" button for cycling through each item individually

In this scenario, I have set up a route to retrieve all the items stored in the question array. However, the issue at hand is that I only want to display a single item on the ejs page instead of all the items. Additionally, I would like to include a next ...

What's the reason for the mousewheel functioning in Chrome but not in Firefox?

I am currently using CSS to enable scrolling up and down a popup page with just the mousewheel, but I'm facing an issue with it not working in FireFox. Surprisingly, it works fine in Chrome with the use of overflow-x:hidden; and overflow-y:auto; prope ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

At what point is it more beneficial to utilize v-model or refs for optimal efficiency?

When working with Vue, we have the flexibility to employ v-model or ref() within a Template ref to effectively alter the data. These two options are often interchangeable in most scenarios. However, I personally struggle to identify any significant advant ...

What is the method used by React's functional setState to identify which fields have been changed?

I've discovered that when using an object as a react state (let [state, setState] = useState({})), and updating it like this: setState(s => { s.a = 42; return s; }) The components depending on s.a do not get re-rendered. However, if you u ...

Whenever I send an Ajax request in my web application, the controller in Laravel responds by providing me with a script within the request parameter

When making this ajax request: $.ajax({ url: "{{URL::to('admin/repcasetracker/getdiscount')}}", data: { serialnumber: serialnumberdata, }, success: function (data) { console.log(data); } }); Controller: public funct ...

Showing a JSON Array in the form of an HTML list

I need help displaying a JSON array in HTML that I received from a PHP server. I tried looping through the array, but when I replaced it with a variable, it stopped working. $(document).ready(function(){ $(document).bind('deviceready', functio ...

AngularJs: Issue encountered while compiling an ng-switch statement

Programming <input type="text" ng-model="user.name" /> <div ng-switch on="user.name"></div> <p ng-switch-default>The winner is</p> <h1 ng-switch-when="John">{{ user.name }}</h1> Can anyone help me? I encountered ...

How to create an onClick event handler in ReactJS and pass 'this' parameter

Here is the code for my component: import React, {PropTypes} from 'react'; export default class Viewdesc extends React.Component { render() { return ( <div className="col-md-12 slide-row"> <div className="col-md-12 overview- ...

Vue.js does not support the Elasticsearch client due to the absence of a Node.js environment

While attempting to implement the elasticsearch client in vue.js, I encountered the requirement for elasticsearch to be used within a node.js environment. Given that Vue.js does not inherently come with a node.js environment, I am seeking an alternative ...

Trouble with jQuery script causing initial word count issue in textarea upon page load

I have implemented a word count textarea jQuery script and I am trying to figure out how to update the word count onload to 2 when the text area initially displays "this example". Currently, it shows 0 words. Although I can set focus on it and move the c ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...

Unexpected trigger of Vue function with parameters from child component

I am encountering an issue with the following component: <template> <button class="button" @[click]="action">{{ text }}</button> </template> <script> export default { name: "Button", props: ...

Sending JSON data from a JSP page to a JavaScript file

I have a JSON string (using Gson) containing data from my database in a JSP file, and I want to pass this information to a JavaScript function. JSP (consulta.jsp): <%@ page language="java" import="java.sql.*" %> <%@ page language="java" import=" ...

Develop a personalized mapping API with a unique image integration for website navigation

Currently, I am in the process of developing a website for my university that will allow users to easily locate all available free food options on campus. My goal is to create a platform where food providers can register their events, have them saved in a ...

What is the method for creating a loop in Angular?

let m = 5; for (let i = 0; i < m; i++) { document.write(i); } What is the output of i in Angular? This code is not functioning as expected. $scope.B = []; angular.forEach([0, 1, 2, 3], function (value, index) { $scope.B.push ...

Tips for obtaining the entire date and time on one continuous line without any breaks or separation

Is there a way to retrieve the current date and time in the format of years, months, days, hours, minutes, seconds, and milliseconds like this? 201802281007475001 Currently, I am getting something like: 2018418112252159 This is my code so far: var dat ...

An unexpected problem with text redirection that should not be happening

I am facing an issue with my HTML text field and post button on my website. Whenever I click the post button to make a post, it redirects to a separate PHP file called post.php which handles PHP and MySQL code for posting. However, I want to avoid this red ...