Use element UI component and back-end interface to upload pictures

Picture upload

All codes:

<el-upload
          ref="up"
          :file-list="form.resourceList"
          :show-file-list="true"
          action="/api/resource/uploadImage"
          list-type="picture-card"
          :auto-upload="true"
          :limit="9"
          :on-exceed="handleExceed"
          :http-request="handleFileSuccess"
        >
          <i slot="default" class="el-icon-plus" />
          <!-- :src="baseApi+'/api/resource/uploadImage'+file.path" -->
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.path"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <!-- preview -->
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>
              <!-- replace -->
              <span
                class="el-upload-list__item-preview"
                @click="handleChange(file)"
              >
                <i class="el-icon-edit" />
              </span>
              <!-- delete -->
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
        <!--  -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
<script>

const defaultForm = {
  resourceList: [],
  deleteIds: [],
};
export default {
  mixins: [form(defaultForm)],
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
    };
  },
  computed: {
    ...mapGetters(["baseApi"]),//Port number
  },
  methods: {
    // Delete picture
    handleRemove(file) {
      // console.log(file,"file")
      this.form.deleteIds.push(file.id);
      for (let i = 0; i < this.form.resourceList.length; i++) {
        if (this.form.resourceList[i].id === file.id) {
          // Splice (index, length) deletes the data with the specified id
          this.form.resourceList.splice(i, 1);
        }
      }
    },
    // Change picture
    handleChange(file) {
      console.log(file, "file");
      this.$confirm("This action will replace the picture with a new one, Continue?", "Tips", {
        confirmButtonText: "determine",
        cancelButtonText: "cancel",
        type: "warning",
      })
        .then(() => {
          // Delete picture first
          let index = 0
          this.form.deleteIds.push(file.id);
          for (let i = 0; i < this.form.resourceList.length; i++) {
            if (this.form.resourceList[i].id === file.id) {
              // Splice (index, length, substitute content) replaces the data of the specified id
              this.form.resourceList.splice(i, 1)
              index = i
            }
          }
          // Then select a new graph
          this.$refs["up"].$refs["upload-inner"].handleClick(); //The upload picture interface appears
          upload("/api/resource/uploadImage", file)
            .then((res) => {
              // Replace old picture with new picture
              this.form.resourceList.splice(index,1,res.data.data)
            })
            .catch((err) => {
              console.log("Return error", err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "Picture editing canceled",
          });
        });
    },
    // preview
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // The number of files exceeds the specified number
    handleExceed(files, fileList) {
      this.$message.warning(
        `Currently, 9 pictures are limited to be selected. This time, it is selected ${files.length} Pictures selected ${
          files.length + fileList.length
        } Pictures`
      )
    },
    //Upload pictures
    handleFileSuccess(file) {
      upload("/api/resource/uploadImage", file.file)
        .then((res) => {
          this.form.resourceList.push(res.data.data)
        })
        .catch((err) => {
          console.log("Return error", err)
        })
    },

   
  },
}
</script>



1, Component part

Upload (element UI)

1. Code

 <el-upload
          ref="up"
          :file-list="form.resourceList"
          :show-file-list="true"
          action="/api/resource/uploadImage"
          list-type="picture-card"
          :auto-upload="true"
          :limit="9"
          :on-exceed="handleExceed"
          :http-request="handleFileSuccess"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
           :src="baseApi+'/api/resource/uploadImage'+file.path""
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <!-- preview -->
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in" />
              </span>
              <!-- replace -->
              <span
                class="el-upload-list__item-preview"
                @click="handleChange(file)"
              >
                <i class="el-icon-edit" />
              </span>
              <!-- delete -->
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </el-upload>
        <!--preview -->
         <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>

2. Explain

(1) Introduction to El upload attribute

  1. file-list

(1) List of uploaded files
(2) Generally, it is the properties obtained by the interface and the parameters returned to the back end (such as form.resourceList)

  1. show-file-list

(1) Display list of uploaded files
(2)boolean type (true or false)

  1. active

(1) Required parameter, upload address
(2) For example, / api/resource/uploadImage in the code is the interface for the backend to upload images

  1. list-type

(1) Type of file list
(2)string type (text / picture / picture card)

  1. auto-upload

(1) Upload files immediately after selecting them
(2)true false

  1. limit

(1) Maximum number of uploads allowed
(2)number type

  1. on-exceed

(1) Hook when the number of files exceeds the limit
(2)function(files, fileList)

  1. http-request

(1) Override the default upload behavior, and you can customize the upload implementation
(2)function

  1. limit

(1) Maximum number of uploads allowed
(2)number type
(2) Picture

  1. src of img

(1)baseApi+'/api/resource/uploadImage'+file.path
(2)baseApi is the port number, / api/resource/uploadImage is the interface address, and file Path is the parameter path from the interface

  1. Preview, modify, delete

(1) Click event trigger method

2, Front and rear end interaction and data transmission

Method all codes

methods: {
    // Delete picture
    handleRemove(file) {
      // console.log(file,"file")
      this.form.deleteIds.push(file.id);
      for (let i = 0; i < this.form.resourceList.length; i++) {
        if (this.form.resourceList[i].id === file.id) {
          // Splice (index, length) deletes the data with the specified id
          this.form.resourceList.splice(i, 1);
        }
      }
    },
    // Change picture
    handleChange(file) {
      console.log(file, "file");
      this.$confirm("This action will replace the picture with a new one, Continue?", "Tips", {
        confirmButtonText: "determine",
        cancelButtonText: "cancel",
        type: "warning",
      })
        .then(() => {
          // Delete picture first
          let index = 0;
          this.form.deleteIds.push(file.id);
          for (let i = 0; i < this.form.resourceList.length; i++) {
            if (this.form.resourceList[i].id === file.id) {
              // Splice (index, length, substitute content) replaces the data of the specified id
              this.form.resourceList.splice(i, 1)
              index = i
            }
          }
          // Then select a new graph
          this.$refs["up"].$refs["upload-inner"].handleClick(); //The upload picture interface appears
          upload("/api/resource/uploadImage", file)
            .then((res) => {
              // Replace old picture with new picture
              this.form.resourceList.splice(index,1,res.data.data)
            })
            .catch((err) => {
              console.log("Return error", err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "Picture editing canceled",
          });
        });
    },
    // preview
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // The number of files exceeds the specified number
    handleExceed(files, fileList) {
      this.$message.warning(
        `Currently, 9 pictures are limited to be selected. This time, it is selected ${files.length} Pictures selected ${
          files.length + fileList.length
        } Pictures`
      );
    },
    //Upload pictures
    handleFileSuccess(file) {
      upload("/api/resource/uploadImage", file.file)
        .then((res) => {
          this.form.resourceList.push(res.data.data);
        })
        .catch((err) => {
          console.log("Return error", err);
        });
    },

An upload method in the framework

import axios from 'axios'
import { getToken } from '@/utils/auth'

export function upload(api, file) {
  var data = new FormData()
  data.append('file', file)
  const config = {
    headers: { 'Authorization': getToken() }
  }
  return axios.post(api, data, config)
}

1. Upload pictures

(1) Code

handleFileSuccess(file) {
      upload("/api/resource/uploadImage", file.file)
        .then((res) => {
          this.form.resourceList.push(res.data.data);
        })
        .catch((err) => {
          console.log("Return error", err);
        });
    },

(2) Explain

  1. res.data.data is an object that needs to be returned to the back end, which contains the type\name\path of the uploaded image
  2. Add res.data Add data to this form. In the resourcelist array
  3. push () is to add elements to the end of the array

2. Delete picture

(1) Code

handleRemove(file) {
      // console.log(file,"file")
      this.form.deleteIds.push(file.id);
      for (let i = 0; i < this.form.resourceList.length; i++) {
        if (this.form.resourceList[i].id === file.id) {
          // Splice (position, length) deletes the data of the specified id
          this.form.resourceList.splice(i, 1);
        }
      }
    },

(2) Explain

  1. Put the id of the deleted image into an array (this.form.deleteIds) and return it to the back end to delete the data in the database
  2. Use the for loop to determine which id it is
  3. Delete the data at the corresponding id position in the picture list parameter (this.form.resourceList) returned to the back end

3. Modify picture

(1) Code

handleChange(file) {
      console.log(file, "file");
      this.$confirm("This action will replace the picture with a new one, Continue?", "Tips", {
        confirmButtonText: "determine",
        cancelButtonText: "cancel",
        type: "warning",
      })
        .then(() => {
          // Delete picture first
          let index = 0;
          this.form.deleteIds.push(file.id);
          for (let i = 0; i < this.form.resourceList.length; i++) {
            if (this.form.resourceList[i].id === file.id) {
              // Splice (index, length, substitute content) replaces the data of the specified id
              this.form.resourceList.splice(i, 1)
              index = i
            }
          }
          // Then select a new picture
          this.$refs["up"].$refs["upload-inner"].handleClick(); //The upload picture interface appears
          upload("/api/resource/uploadImage", file)
            .then((res) => {
              // Replace old picture with new picture
              this.form.resourceList.splice(index,1,res.data.data)
            })
            .catch((err) => {
              console.log("Return error", err)
            })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "Picture editing canceled",
          })
        })
    },

(2) Explain

1. The method of deleting pictures first and then uploading them is used to modify pictures, but prompt is required. Otherwise, once you click Edit, the pictures will be deleted, and the user experience is poor.

  1. The index variable is used to record the position of the old picture in the array, so that it can be inserted into the corresponding position when uploading a new picture later.
  2. this.$refs["up"].$refs["upload-inner"].handleClick(); After clicking, the upload interface appears to select pictures. (this.$refs. (ref value). Method () can use all methods of the component)
  3. this.form.resourceList.splice(index,1,res.data.data) the new picture replaces the old one
  4. splice(index,length,[item]) to delete, replace and add elements

(1) The first parameter is where to insert the element
(2) The second parameter is passed in. How many elements do you want to delete
(3) The third element is used to replace the previous element
(4) When passing a parameter: when passing a parameter, it means that it is intercepted from the position of the parameter to the end
(5) Pass two parameters. The first parameter represents the starting position and the second parameter represents the number to be intercepted; If the second parameter is 0, it means that the returned empty array is not intercepted, and the original array remains unchanged
(6) When passing three parameters: if the second parameter is 0, add item at index; If the second parameter is not 0, delete the length item from the index and add the item
(7) Summary: delete: splice(index,length); Add splice(index,0,item); Replace splice (index,1,item)

4. Preview picture

(1) Code

// preview pictures
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }

5. Limit the number of pictures

(1) Code

 // The number of files exceeds the specified number
    handleExceed(files, fileList) {
      this.$message.warning(
        `Currently, 9 pictures are limited to be selected. This time, it is selected ${files.length} Pictures selected ${
          files.length + fileList.length
        } Pictures`
      )
    },

Text will be prompted when the number of pictures exceeds the limit

Keywords: Front-end Vue Vue.js elementUI

Added by searchman on Wed, 22 Dec 2021 09:52:10 +0200