search
HomeWeb Front-endFront-end Q&AExamples to explain how Vue implements the file upload function

Vue is a popular JavaScript framework that is widely used in front-end development. In Vue, file upload is a very common requirement. This article will introduce how to write Vue upload files.

1. Installation dependencies

Vue file upload requires the use of axios and vue-router, so we need to install these two dependencies:

npm install axios vue-router --save

2. HTML Code

The following is the HTML code for Vue to upload files:

<template>
  <div>
    <input>
    <button>上传</button>
  </div>
</template>

Among them, onFileChange is an event triggered when a file is selected, and upload is an event triggered when the upload button is clicked.

3. JavaScript code

Next, we need to write Vue’s JavaScript code:

<script>
  import axios from &#39;axios&#39;
  import router from &#39;vue-router&#39;
  
  export default {
    name: &#39;file-upload&#39;,
    data () {
      return {
        file: null,
        errorMsg: &#39;&#39;
      }
    },
    methods: {
      onFileChange (event) {
        this.file = event.target.files[0];
      },
      upload () {
        let formData = new FormData();
        formData.append(&#39;file&#39;, this.file);
        
        let token = localStorage.getItem(&#39;token&#39;);
        if (token) {
          axios.post(&#39;/api/upload&#39;, formData, {
            headers: {
              &#39;Authorization&#39;: &#39;Bearer &#39; + token
            }
          })
          .then(response => {
            router.push(&#39;/success&#39;);
          })
          .catch(error => {
            this.errorMsg = &#39;上传文件失败&#39;;
          })
        }
      }
    }
  }
</script>

Among them, we first import axios and vue-router dependencies, and then define A data object contains two attributes: file and errorMsg, which represent files and error messages respectively.

Next, we defined two methods: onFileChange and upload. The onFileChange method is triggered when a file is selected and saves the selected file in the file attribute of the data object. The upload method is triggered when the upload button is clicked. First, a FormData object is created, and then the file is uploaded to the server through the axios.post method. After the upload is successful, vue-router is used to jump to the success page. An error occurs during the upload process. The errorMsg attribute is assigned a value of failure to upload the file.

4. Summary

The writing method of Vue uploading files is relatively simple. You only need to understand the usage of two dependencies, axios and vue-router, to realize the file upload function. I hope the introduction in this article can be helpful to everyone.

The above is the detailed content of Examples to explain how Vue implements the file upload function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.