springboot + element-plus实现文件上传

springboot + element-plus实现文件上传

      • 环境
      • 效果
      • 后端
      • 前端

环境

jdk17 + vue3

效果

springboot + element-plus实现文件上传_第1张图片

后端

后端上传图片后返回图片的url
前端得到结果后在页面展示

package com.example.demo.controller;

import com.example.demo.util.Res;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    private final ResourceLoader resourceLoader;

    public UploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    @PostMapping("/file")
    public Res<Object> upload(@RequestParam("file")  MultipartFile file, HttpServletRequest request){
        try{
            File dir = new File(resourceLoader.getResource("classpath:/static/").getFile(), "upload");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String fileName = UUID.randomUUID().toString();

            file.transferTo(new File(dir.getAbsolutePath() + File.separator + fileName + ".png"));

            String url = request.getScheme() + "://" +request.getServerName() +":"+request.getServerPort() + "/upload/" +fileName +".png";

            return Res.success("文件上传成功",url);
        }catch (Exception ex) {
            return Res.error("文件上传失败");
        }
    }
}

前端

用的Element-plus的upload组件
handleAvatarSuccess 文件上传成功的回调
在这个案例中我们把上传成功后的url赋值给imageUrl 方便在前端展示

<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue';


const imageUrl = ref("")

const handleAvatarSuccess = (res, file) => {
    if (res.code !== 200) {
        return ElMessage.error("文件上传失败");
    }
    imageUrl.value = res.data
    return ElMessage.success("文件上传成功");
}

const beforeAvatarUpload = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png' && rawFile.type !== 'image/jpg') {
        ElMessage.error('Avatar picture must be JPG/PNG/JPEG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
}
</script>

<template>
    <div class="upload">
        <el-upload class="avatar-uploader" action="http://127.0.0.1:8000/upload/file" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
    </div>
</template>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>

你可能感兴趣的:(spring,boot,后端,java)