Implementation example of Vue+Element+Springboot image upload

Implementation example of Vue+Element+Springboot image upload

Recently, I happened to be in touch with the vue+springboot front-end and back-end separation project, and used the picture upload function and recorded it.

Part of the form code to be submitted on the front end

<el-form-item label="Cover image">
                <el-upload v-model="dataForm.title"
                        class="avatar-uploader"
                        :limit="1"
                        list-type="picture-card"
                        :on-preview="handlePictureCardPreview"
                        multiple
                        :http-request="uploadFile"
                        :on-remove="handleRemove"
                        :on-change='changeUpload'
                        :file-list="images">
                    <i class="el-icon-plus"></i>
                </el-upload>
            </el-form-item>

Explanation of elements in el-upload:

  • on-preview: An event that occurs when you click an uploaded file in the file list
  • on-remove: The method called when deleting a file
  • on-change: An event when the file status changes. It will be called when adding a file, uploading successfully, or uploading failed.
  • file-list: uploaded file list or default echo data display rendering

retrun and data

return {
                images: [{name: 'food.jpg', url: 'upload/2022/web/20210329194832973.png'}],
                imageUrl: '',
                fileList: [], // File upload data (multiple files in one)
                dialogImageUrl: '',
                dialogVisible: false,
                options: [],
                content: '',
                editorOption: {},
                visible: false,
                dataForm: {
                    id: 0,
                    title: '',
                    content: '',
                    bz: ''
                },
                tempKey: -666666 // Temporary key, used to solve the problem that the half-selected state of the tree item cannot be passed to the backend interface. # To be optimized}

Preview, upload, and delete images

changeUpload: function(file, fileList) {//Preview image this.fileList = fileList;
            },
            uploadFile(file){

            },
            handleRemove(file, fileList) {
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },

Here I use the fomrData object to submit, because I only need to upload a single cover image and add some other form content.

// Form submission dataFormSubmit () {
                const form = new FormData() // FormData object form.append('file', this.fileList);
                form.append('title', this.dataForm.title);
                form.append('content', this.$refs.text.value);
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.$http({
                            url: this.$http.adornUrl(`/sys/inform/${!this.dataForm.id ? 'save' : 'update'}`),
                            method: 'post',
                            data:form
                        }).then(({data}) => {
                            if (data && data.code === 0) {
                                this.$message({
                                    message: 'Operation successful',
                                    type: 'success',
                                    duration: 1500,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refreshDataList')
                                    }
                                })
                            } else {
                                this.$message.error(data.msg)
                            }
                        })
                    }
                })
            }

In the background, through HttpServletRequest request--WebUtils

.getNativeRequest(request, MultipartHttpServletRequest.class) to get the file request and parse the file to the server or local

/**
 * @author lyy
 * Save PC-background upload file*/
@RequestMapping(value = "sys/file/save", method = {RequestMethod.POST, RequestMethod.GET})
@Transactional
public R save(HttpServletRequest request) {
    String classify = request.getParameter("classify");
    MultipartHttpServletRequest multipartRequest = WebUtils
            .getNativeRequest(request, MultipartHttpServletRequest.class);
    String fileName = "";
    if (multipartRequest != null) {
        Iterator<String> names = multipartRequest.getFileNames();
        while (names.hasNext()) {
            List<MultipartFile> files = multipartRequest.getFiles(names.next());
            if (files != null && files.size() > 0) {
                for (MultipartFile file : files) {
                    fileName = file.getOriginalFilename();
                    String SUFFIX = FileUtil.getFileExt(fileName);
                    File uFile = new File();
                    uFile.setFileName(fileName);
                    uFile.setClassify(classify);
                    uFile.setCreateTime(new Date());
                    uFile.setFileType(SUFFIX);
                    String uuid = FileUtil.uuid();
                    try {
                        uFile.setPath(uploadFile(uuid,file) +uuid+"."+SUFFIX);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                     fileService.save(uFile);
                }
            }
        }
    }
    return R.ok();
}

Static method for uploading files to local

/**
     * Upload file *@author lyy
     * @param file
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    public static String uploadFile(String uuid, MultipartFile file) throws IllegalStateException, IOException {
        String defaultUrl = MyFileConfig.getFilePath();
        String Directory = java.io.File.separator;
        String realUrl = defaultUrl + Directory;
        java.io.File realFile = new java.io.File(realUrl);
        if (!realFile.exists() && !realFile.isDirectory()) {
            realFile.mkdirs();
        }
        String fullFile = realUrl + uuid + "." + FileUtil.getFileExt(file.getOriginalFilename());
        file.transferTo(new java.io.File(fullFile));
        String relativePlanUrl = Directory;
        return relativePlanUrl.replaceAll("\\", "/");
    }

This is the end of this article about the implementation example of Vue+Element+Springboot image upload. For more relevant Vue+Element+Springboot image upload content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue+SSM realizes the preview effect of picture upload
  • Vue+axios sample code for uploading pictures and recognizing faces
  • Problems encountered when uploading images using axios in Vue
  • Vue.js cloud storage realizes image upload function
  • Public multi-type attachment image upload area in Vue page and applicable folding panel (sample code)

<<:  Call js function or js variable in html's img src="" to dynamically specify the image path

>>:  Analysis and redesign of music player apps (application software) How to design a beautiful music player interface

Recommend

Solution to the problem of invalid width setting for label and span

By default, setting width for label and span is in...

MySQL 5.5.27 winx64 installation and configuration method graphic tutorial

1. Installation Package MYSQL service download ad...

How to implement scheduled backup of MySQL database

1. Create a shell script vim backupdb.sh Create t...

Some indicators of excellent web front-end design

The accessibility of web pages seems to be somethi...

JavaScript Objects (details)

Table of contents JavaScript Objects 1. Definitio...

CSS solution for centering elements with variable width and height

1. Horizontal center Public code: html: <div c...

Pitfalls and solutions encountered in MySQL timestamp comparison query

Table of contents Pitfalls encountered in timesta...

Summary of js execution context and scope

Table of contents Preface text 1. Concepts relate...

MySQL query optimization using custom variables

Table of contents Optimizing sorting queries Avoi...

Today I encountered a very strange li a click problem and solved it myself

...It's like this, today I was going to make a...

What does the "a" in rgba mean? CSS RGBA Color Guide

RGBA is a CSS color that can set color value and ...

Docker container data volume named mount and anonymous mount issues

Table of contents What is a container data volume...

Detailed explanation of the available environment variables in Docker Compose

Several parts of Compose deal with environment va...

Detailed steps to build an independent mail server on Centos7.9

Table of contents Preface 1. Configure intranet D...

VMware, nmap, burpsuite installation tutorial

Table of contents VMware BurpSuite 1. Virtual mac...