SoFunction
Updated on 2025-04-12

Implement image drag and drop upload function based on Vue3

introduction

In front-end development, user experience is crucial, and image upload is one of the features that is often needed in many web applications. In order to improve the user's interactive experience, the drag-and-drop upload function can reduce the user's operation steps and allow users to upload files more intuitively. This article will explain how to implement a simple image drag-and-drop upload using Vue 3 and its new Composition API (setup syntax sugar).

Project preparation

First, you need to install the Vue CLI. Make sure you have installed and npm, and then you can install the Vue CLI using the following command:

npm install -g @vue/cli

Next, create a new Vue project through the command:

vue create drag-and-drop-upload

Select the desired configuration (recommended to select the default configuration), and then enter the project directory:

cd drag-and-drop-upload

Now we need to install additional libraries for handling file uploads. We can useaxiosSend HTTP request:

npm install axios

Create drag component

existsrc/componentsCreate a directory calledcomponent file. Next, we will implement the logic of drag and drop upload.

<template>
  <div
    class="upload-area"
    @
    @="handleDrop"
    :class="{ 'is-dragover': isDragOver }"
    @dragenter="isDragOver = true"
    @dragleave="isDragOver = false"
  >
    <p v-if="!file">Drag and drop the image here,Or click to select file</p>
    <p v-if="file">{{  }}</p>
    <input type="file" @change="handleFileChange" accept="image/*" style="display: none;" ref="fileInput" />
    <button @click="selectFile">Select a file</button>
    <button @click="uploadFile" :disabled="!file">Upload</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const file = ref(null);
const isDragOver = ref(false);
const fileInput = ref(null);

const handleFileChange = (event) => {
  const selectedFile = [0];
  if (selectedFile && ('image/')) {
     = selectedFile;
  } else    alert('Please select a valid image file');
  }
};

const handleDrop = (event) => {
  const droppedFile = [0];
  if (droppedFile && ('image/')) {
     = droppedFile;
  } else {
    alert('You can only upload image files');
  }
   = false; // Reset drag over status
};

const selectFile = () => {
  ();
};

const uploadFile = async () => {
  if (!) return;

  const formData = new FormData();
  ('file', );

  try {
    const response = await ('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    alert('Uploaded successfully:' + );
  } catch (error) {
    alert('Upload failed:' + );
  }
};
</script>

<style scoped>
.upload-area {
  border: 2px dashed #ccc;
  border-radius: 10px;
  width: 300px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  transition: background-color 0.3s;
}

.-dragover {
  background-color: #f0f8ff;
}

button {
  margin-top: 10px;
}
</style>

Code parsing

Template section

  • upload-areaClass: This is a div used to display the upload area, including listening to drag events and related prompts.
  • @and@: These two instructions block the default browser behavior and ensure that files can be dragged into the area.
  • v-ifUsed to update interface information according to user operations.

Logical part

  • Status Management:userefCreate a responsivefileand oneisDragOverUsed to manage drag and drop status.

  • File selection and drag processing

    • handleFileChange: Process file selection (file selected in the input box).
    • handleDrop: Process files dragged to the upload area.
  • File upload

    • Uploading files will be usedaxiosSend a POST request to upload the selected image to the specified server address.

Usage Components

existUse this component in:

<template>
  <div >
    <h1>Image drag and drop upload example</h1>
    <DragAndDropUpload />
  </div>
</template>

<script setup>
import DragAndDropUpload from './components/';
</script>

<style>
#app {
  text-align: center;
  margin-top: 50px;
}
</style>

in conclusion

The above is a complete example of using Vue 3 and setup syntax sugar to implement image drag and drop upload function. Through the above steps, you can easily integrate this feature in your front-end application, greatly improving the user's interactive experience.

This is the article about using Vue3 to implement the image drag and drop upload function. For more related Vue3 image drag and drop upload content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!