Element : upload

Set the upload address, request header (token/Content-Type), and upload file nameCopy the code

Upload component implementation

<template>
  <el-upload
    class="avatar-uploader"
    # set the image upload address
    :action="uploadUrl"
    Set the request header
    :headers="headers"
    # set the name of the uploaded file field (according to the interface parameter)
    name="fileName"
    # upload file before processing function
    :before-upload="beforeAvatarUpload"
    # callback function after successful upload
    :on-success="handleAvatarSuccess"
    :show-file-list="false">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>
Copy the code
<script>
import { baseURL, KEYS } from '@/config'
import { getStorageItem } from '@/utils'
export default {
  data() {
    return {
        imageUrl: ' '}}, computed: {// Set the request headerheaders() {
      return{// Set content-type to multipart/form-data'ContentType': 'multipart/form-data'/ / set the token'token': getStorageItem(keys.token),}}, // Set the upload addressuploadUrl() {// baseURL is the server path, which is also the base path of AXIosreturn baseURL + '/account/headImg'
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if(! isImg) { this.$message.error('Upload profile picture in JPG/PNG format only! ')}if(! isLt2M) { this.$message.error('Upload profile picture size cannot exceed 2MB! ')}returnIsImg && isLt2M}, handleAvatarSuccess(res, file) { This. ImageUrl = res.data + ensures that images are refreshed in real time'? ' + Math.random()
    }
  }
}
</script>
Copy the code