springBoot——文件上传结合ElementUi

1.使用ElementUi编写文件上传的表单

01.设置文件上传表单的相关属性

  • ref:表达的引用
  • action:文件上传的地址
  • :show-file-list:是否显示已选中的图片
  • :on-preview:点击放大图片时钩子函数,调用具体的方法
  • :before-remove:文件上传之前调用的方法,用于验证文件格式等信息
  • :on-remove:移除文件时的钩子函数
  • :before-remove:移除文件之前要执行的函数
  • :auto-upload:是否自动上传文件,一般设置为false
  • :data:上传文件时同时附带表单中的其他数据
  • multiple:支持多选文件
  • :limit="3":限制文件参数3个
  • :on-exceed:超出限制文件参数时执行的函数
  • :file-list="fileList":存储上传文件的列表
  • accept="image/jpeg,image/jpg,image/png":弹出文件选择框时,会自动筛选定义好的文件格式
  • :on-success:上传文件成功后执行的函数
  • list-type:已选中的文件显示的方式
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="活动名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="活动图片" prop="name">
            <el-upload
                class="upload-demo"
                ref="upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="true"
                :on-preview="handlePreview"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :auto-upload="false"
                :data="ruleForm"
                multiple
                :limit="3"
                :on-exceed="handleExceed"
                :file-list="fileList"
                accept="image/jpeg,image/jpg,image/png"
                :on-success="handleSuccess"
                list-type="picture-card">
                <el-button size="small" type="primary">选择文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500M</div>
            </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">点击上传</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
    </el-form>

02.编写script模块

        设置date:

export default {
    data() {
        return {
            fileList: [],
            ruleForm: {
                name: '',
            },
            rules: {
                name: [
                    {required: true, message: '请输入活动名称', trigger: 'blur'},
                    {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                ]
            }
        };
    },
}

        定义methods:

 methods: {
        //表单提交
        submitForm(formName) {
            const _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    _this.$refs.upload.submit();
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //图片上传前验证图片参数信息
        beforeUpload(file){
            let type = file.name.substring(file.name.lastIndexOf(".")+1);
            const types = ["jpeg","jpg","png"];
            if (types.indexOf(type)===-1){
                this.$message.error("只能上传jpg/png格式!");
                return false;s
            }
            if (file.size>5000*1024){
                this.$message.error("图片大小不能超过5M");
                return false;
            }
        },
        //移除图片时执行的方法
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        //点击放大镜执行的方法
        handlePreview(file) {
            console.log(file);
        },
        //超出限制文件参数时执行的函数
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
        },
        //移除文件之前要执行的函数
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}?`);
        },
        //文件上传成功后执行的函数
        handleSuccess(response){
            this.$message.success("上传文件成功!"+response)
        }
    }

        效果图:

 

2.实现后端

01.在后端项目所在的目录的下创建static目录用于存储下载的文件,该目录与src和target为同级目录

02.编写图片类,用于接收图片相关参数,生成get和set方法

package com.ck.pojo;
//用于接收图片相关参数的类
public class Pictures {
    private Integer id;
    private String name;
    private String url;

    。。。
}

02.编写controller类

@RestController
@RequestMapping("/members")
public class UploadController {
    @PostMapping("/upload")
    public ReturnResult imporDate(MultipartFile file, HttpServletRequest request, Pictures pictures) throws IOException {
        if (file != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            //获取当前日期为保存文件的目录名
            String newFileDate = sdf.format(new Date());
            //获取static文件夹所在的位置,并在static下创建upload目录,在upload目录下创建newFileDate目录用于保存图片
            String realPath = request.getServletContext().getRealPath("/upload/"+newFileDate);
            //通过获取到的路径创建目录
            File folder = new File(realPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            //给文件重命名
            //获取原有的文件名
            String oldFolderName = file.getOriginalFilename();
            //生成新的文件名
            String newFolderName = UUID.randomUUID() + oldFolderName.substring(oldFolderName.lastIndexOf("."));
            //保存文件到newFileDate目录下,并命名为newFolderName
            file.transferTo(new File(folder, newFolderName));
            //获取文件的相关参数保存至数据库中
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/upload"+"/" + newFileDate+"/" + newFolderName;
            pictures.setUrl(url);
            pictures.setId(new Date().getTime());
            System.out.println(url);
            //这里调用service。。。
            return ReturnResultUtils.returnSuccess(200,"文件上传成功");
        }else {
            return ReturnResultUtils.returnFail(404,"文件为空");
        }
    }
}

效果图:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值