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

Implementation of local migration of docker images

I've been learning Docker recently, and I oft...

MySQL 8.0.19 installation and configuration method graphic tutorial

This article records the installation and configu...

How to isolate users in docker containers

In the previous article "Understanding UID a...

Ubuntu regularly executes Python script example code

Original link: https://vien.tech/article/157 Pref...

Docker connects to a container through a port

Docker container connection 1. Network port mappi...

HTML table tag tutorial (11): horizontal alignment attribute ALIGN

In the horizontal direction, you can set the alig...

LinkedIn revamps to simplify website browsing

Business social networking site LinkedIn recently...

Win10 uses Tsinghua source to quickly install pytorch-GPU version (recommended)

Check whether your cuda is installed Type in the ...

Vue implements drag and drop or click to upload pictures

This article shares the specific code of Vue to a...

How to use rem adaptation in Vue

1. Development environment vue 2. Computer system...

A brief discussion of 12 classic problems in Angular

Table of contents 1. Please explain what are the ...

Comparison of two implementation methods of Vue drop-down list

Two implementations of Vue drop-down list The fir...