Vue file upload - how to upload? And refresh token loss problem

1. Vue file upload

The method we adopt is to use the element component to implement file upload:

Refer to the official website: Element - The world's most popular Vue UI framework

1. Click Upload, the reference code is as follows:

<el-upload
  class="upload-demo"
  action="https://jsonplaceholder.typicode.com/posts/"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  multiple
  :limit="3"
  :on-exceed="handleExceed"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<script>
  export default {
    data() {
      return {
        fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      };
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }?`);
      }
    }
  }
</script>

2. The effect is as follows:

 3. Some common attributes:

action, a required parameter, the URL to upload.

headers, set the upload request header.

multiple, whether to support multiple selection of files, type boolean.

show-file-list, whether to display the list of uploaded files, type boolean.

drag, whether to enable drag and drop upload, type boolean.

on-success, the hook when the file upload is successful.

You can limit the number of uploaded files and define the behavior when the limit is exceeded by setting limitand .on-exceed

before-removeFile removal can be blocked through settings .

Note: You can pass in a custom upload button type and text prompt (tip) through the slot.

2. When refreshing or uploading for the first time, the upload fails

The reason for this problem is that the Token stored in VueX is lost when the page is refreshed in the front-end login business.

Generally, there are two ways to write our headers. When we adopt the first method below, the Token loss problem will occur.

 写法一:

<template>
<div>
<el-upload
            class="upload"
            :action="actionUrl"
            :on-success="handleUploadSuccess"
            :headers="headers"
            :show-file-list="false"
          >
            <el-button size="small">
              <i class="el-icon-upload el-icon--left">点击上传</i>
            </el-button>
          </el-upload>
</div>
</template>

<script>
export default {
  data() {
    return {
headers: {
   token: this.$store.state.authToken
},
};
}
</script>

Because in this way of writing, the token is fixed, the store is cleared when the page is refreshed, and the local token is empty.

1. It is easier to understand this way: For example, when implementing the user login and registration business, the user name and password registered by the user are sent to the server through an ajax request (you can put the data in the request header), and the server returns an account-specific Token, which will be Tokens are stored in the general store, but refreshing the page will cause the Token value in the store to be lost and become the initial value, which is an empty string, resulting in the loss of a series of subsequent actions that need to be used to determine whether the Token exists.

2. Causes of this problem:

The superficial reason is that the token is not carried to the server, and the ajax request carrying the token cannot be sent, which causes the page to fail to render the data returned by the server. The deeper reason is that the data stored in Vuex is not persistent, and the data in the store is stored in the running memory. , once the page is refreshed, the Vue instance will be reloaded, and the data in the store will become the initial value, that is, the Token value will be an empty string.

3. The solution is to use the second way of writing, because our token is also dynamic, so we can use the calculated property to obtain it dynamically:

 写法一:

<template>
<div>
<el-upload
            class="upload"
            :action="actionUrl"
            :on-success="handleUploadSuccess"
            :headers="{token:token}"
            :show-file-list="false"
          >
            <el-button size="small">
              <i class="el-icon-upload el-icon--left">点击上传</i>
            </el-button>
          </el-upload>
</div>
</template>

<script>
export default {
  data() {
    return {
};
},
computed:{
    token(){
      return this.$store.state.authToken;
    }

  },
</script>

4. Some other solutions, for reference only:

 1) Local storage: change non-persistent storage into persistent storage

You can set the initial value of the token in the warehouse to localStorage.getItem('token'), so that the initial value is still an empty string before local storage is performed, so that the token in the local storage can be used when the page is mounted. It should be noted that other modules also need to send a request with token to the server when mounting, otherwise the locally stored token cannot be obtained, and the request can be sent in the app component.

2) Store the token in sessionStorage and cookie, but the character strings that can be stored in cookie are limited, so it is not suitable for storage with a large space. The data stored in sessionStorage will be cleared after the browser is closed. According to my actual needs, choose to use local storage

3) Use a plugin vuex-persistedstate for vuex to process and store state between page refreshes. Need to import and register when creating a warehouse

import createPersistedState from 'vuex-persistedstate'
 
const store = new Vuex.Store({
  // ...
  plugins: [
    createPersistedState()
  ]
})

 

Guess you like

Origin blog.csdn.net/coinisi_li/article/details/126992122