vue含附件的表单提交

此帖的主要目的是记录以下三点:
1、使用elementUI的上传附件。
2、vue使用FormData,向接口传送表单数据(含附件)。
3、接口从HttpServletRequest中获取请求数据,通过@RequestPart(“USER_PHOTO_”) MultipartFile USER_PHOTO_获取附件数据。

1、使用elementUI的上传附件

                            <el-upload action="uploadAction" list-type="picture-card"
                                       :on-preview="handlePictureCardPreview" 
                                       :on-remove="handleRemove"
                                       :limit="1" 
                                       :show-file-list="true" 
                                       name="img" 
                                       ref="upload" 
                                       :data="userForm"
                                       accept="image/png,image/gif,image/jpg,image/jpeg"
                                       :on-exceed="handleExceed" 
                                       :auto-upload="false"
                                       :on-error="uploadError" 
                                       :before-upload="handleBeforeUpload"
                                       :on-change="changeFile">
                                <i class="el-icon-plus">i>
                            el-upload>
 //文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
            onChange(file, fileList) {
                console.log(file.raw);
                console.log(this.$refs.userPhoto);
                this.userForm.imageUrl = URL.createObjectURL(file.raw);
            },
            
            // 上传文件之前的钩子
            handleBeforeUpload(file) {
                console.log('按钮', this.titleMap)
                if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type ===
                    'image/jpeg')) {
                    this.$notify.warning({
                        title: '警告',
                        message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
                    })
                }
                let size = file.size / 1024 / 1024 / 2;
                if (size > 2) {
                    this.$notify.warning({
                        title: '警告',
                        message: '图片大小必须小于2M'
                    })
                }

            },
            //图片上传超过数量限制
            handleExceed(files, fileList) {
                this.$message.error("上传图片不能超过1张!");
            },
            handleRemove(file, fileList) {
                this.$message.error("删除成功!");
            },
            // 图片上传失败时
            uploadError() {
                this.$message.error("图片上传失败!");
            },
            //预览图片
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            //文件改变时 on-change方法 ,fileList[0].raw 就是传给后端的值
            //filelist这个对象里面有很多属性,我们上传文件时,实际上传的是filelist列表中每一项的raw,只有raw可以正常上传, 获取到文件后,需要定义变量保存文件。所以需要获取filelist中的raw进行保存。
            //这里我用的formdata上传多文件,console打印formdata,文件在控制台中显示的格式为binary。

            changeFile(file, fileList) {
                this.userForm.imageUrl = fileList[0].raw
            },

2、vue使用FormData,向接口传送表单数据(含附件)
2-1:画面html部分


            
            <el-dialog :title="title" :visible.sync="editFormVisible" width="35%" @click='closeDialog("edit")'>
                
                
                <div style="width: 50%">
                    <el-form label-width="90px" ref="userForm" :model="userForm" :rules="rules">
                        <el-form-item label="ID:" prop="ID_" style="display: none">
                            <el-input size="small" v-model="userForm.ID_" auto-complete="off"
                                      style="display: none">el-input>
                        el-form-item>
                        <el-form-item label="员工工号:" prop="USER_CODE_">
                            
                            <el-input size="small" v-model="userForm.USER_CODE_" auto-complete="off"
                                      placeholder="请输入员工工号">el-input>
                        el-form-item>
                        <el-form-item label="员工姓名:" prop="USER_NAME_" class="form_item">
                            <el-input size="small" v-model="userForm.USER_NAME_" auto-complete="off"
                                      placeholder="请输入员工姓名">el-input>
                        el-form-item>
                        <el-form-item label="所属部门:" prop="DEPT_NAME_" class="form_item">
                            <el-select size="small" v-model="userForm.DEPT_NAME_" placeholder="请选择" style="width: 100%"
                                       @change="selectPost">
                                <el-option v-for="item in dept" :key="item.key" :label="item.DEPT_NAME_"
                                           :value="item.DEPT_CODE_"/>
                            el-select>
                        el-form-item>
                        <el-form-item label="岗位:" prop="POST_NAME_" class="form_item">
                            <el-select size="small" v-model="userForm.POST_NAME_" placeholder="请选择" style="width: 100%">
                                <el-option v-for="item in post" :key="item.key" :label="item.POST_NAME_"
                                           :value="item.POST_CODE_"/>
                            el-select>
                        el-form-item>
                        <el-form-item label="角色:" prop="ROLE_" class="form_item">
                            <el-select size="small" v-model="userForm.ROLE_" placeholder="请选择" style="width: 100%">
                                <el-option label="主任" value="1">el-option>
                                <el-option label="职员" value="2">el-option>
                            el-select>
                        el-form-item>
                        <el-form-item label="联系方式" prop="USER_PHONE_" class="form_item">
                            <el-input size="small" v-model="userForm.USER_PHONE_" placeholder="请输入手机号">el-input>
                        el-form-item>
                        <el-form-item label="出生日期" prop="USER_BIRTHDAY_" class="form_item">
                            <el-date-picker v-model="userForm.USER_BIRTHDAY_" type="date"
                                            format="yyyy 年 MM ⽉ dd ⽇"
                                            value-format="yyyy-MM-dd"
                                            placeholder="选择日期">el-date-picker>
                        el-form-item>
                        <el-form-item label="性别" prop="USER_SEX_" class="form_item">
                            <el-radio v-model="userForm.USER_SEX_" label="">el-radio>
                            <el-radio v-model="userForm.USER_SEX_" label="">el-radio>
                        el-form-item>
                        <el-form-item label="照片" class="form_item">

                            <el-upload action="uploadAction" list-type="picture-card"
                                       :on-preview="handlePictureCardPreview"
                                       :on-remove="handleRemove"
                                       :limit="1"
                                       :show-file-list="true"
                                       name="img"
                                       ref="upload"
                                       :data="userForm"
                                       accept="image/png,image/gif,image/jpg,image/jpeg"
                                       :on-exceed="handleExceed"
                                       :auto-upload="false"
                                       :on-error="uploadError"
                                       :before-upload="handleBeforeUpload"
                                       :on-change="changeFile">
                                <i class="el-icon-plus">i>
                            el-upload>
                        el-form-item>
                    el-form>
                div>
                <div slot="footer">
                    <el-button size="small" @click='closeDialog("edit")'>取消el-button>
                    <el-button size="small" type="primary" :loading="loading" @click="submitForm('userForm')">保存
                    el-button>
                div>
            el-dialog>

2-2:vue.js部分

//2-2-1  在data()中声明数据
                // 编辑与添加
                userForm: {
                    ID_: '',
                    USER_CODE_: '',
                    USER_NAME_: '',
                    DEPT_NAME_: '',
                    POST_NAME_: '',
                    ROLE_: '',
                    USER_PHONE_: '',
                    USER_BIRTHDAY_: '',
                    USER_SEX_: '',
                    photo: '',
                    imageUrl: ''
                },
 //2-2-2   在methods{}中写与后台联动的函数
  //新增用户
            insertUser(params) {
                let that = this;
                let fd = new FormData();
                fd.append('USER_CODE_', params.USER_CODE_);
                fd.append('USER_NAME_', params.USER_NAME_);
                fd.append('DEPT_NAME_', params.DEPT_NAME_);
                fd.append('POST_NAME_', params.POST_NAME_);
                fd.append('ROLE_', params.ROLE_);
                fd.append('USER_PHONE_', params.USER_PHONE_);
                fd.append('USER_BIRTHDAY_', params.USER_BIRTHDAY_);
                fd.append('USER_SEX_', params.USER_SEX_);
                fd.append('USER_PHOTO_', that.userForm.imageUrl);

                axios({
                    method: 'POST',
                    url: '/api/insertUser',
                    data:fd,
                    timeout: 2000,
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                }).then(function (res) {
                    console.log(res);
                    if (res.data.success) {
                        that.editFormVisible = false;//关闭新增窗口
                        that.$message({
                            message: '添加用户成功',
                            type: 'success'
                        });
                        that.selectUser();//调用查询方法,目的是刷新页面
                    }
                    else {
                        that.$message.error('添加用户失败');
                    }
                }).catch(function (err) {
                    /*请求失败*/
                    that.$message.error('添加用户失败');
                });
            }

2-3;数据库表结构
vue含附件的表单提交_第1张图片2-4:后台接口部分(没用实体类)

//下面是controller层
  //新增用户
    @RequestMapping(value = "insertUser")
    @ResponseBody
    public Map<String, Object> insertUser( @RequestPart("USER_PHOTO_") MultipartFile USER_PHOTO_, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        Map<String, Object> result = new HashMap<String, Object>();

        String USER_CODE_ = request.getParameter("USER_CODE_");
        String USER_NAME_ = request.getParameter("USER_NAME_");
        String DEPT_NAME_ = request.getParameter("DEPT_NAME_");
        String POST_NAME_ = request.getParameter("POST_NAME_");
        String ROLE_ = request.getParameter("ROLE_");
        String USER_PHONE_ = request.getParameter("USER_PHONE_");
        String USER_SEX_ = request.getParameter("USER_SEX_");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date USER_BIRTHDAY_ = null;//String类型改成Date
        try {
            USER_BIRTHDAY_ = formatter.parse(request.getParameter("USER_BIRTHDAY_"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        InputStream userPhoto_InputStream = null;
        Integer userPhoto_Length_ = null;
        try {
            userPhoto_InputStream = USER_PHOTO_.getInputStream();// 获得上传二进制流
            userPhoto_Length_ = (int) USER_PHOTO_.getSize();
//            if (SEAL_LENGTH_ >= BaseConfig.getMaxUploadSize()) {// 上传文件大小限制检查
//                throw new Exception(getLocaleMessage("errors.uploadingFilesIsTooBig", null, request));
//            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String ID_ = BaseUtils.getUuid();
            if (userService.insertUser(ID_, USER_CODE_, USER_NAME_, DEPT_NAME_, POST_NAME_, ROLE_, USER_PHONE_, USER_BIRTHDAY_, USER_SEX_, userPhoto_InputStream, userPhoto_Length_) == 0) {
                throw new Exception();
            }
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Credentials", "true");

            result.put("success", true);
        } catch (Exception e) {
            System.out.println(e);
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            response.setHeader("Access-Control-Allow-Credentials", "true");

            result.put("success", false);
            StringWriter stringWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(stringWriter));
        }

        return result;
    }


//下面是service层和impl层,没有实体类

    /*
     * 新增用户
     */
    public int insertUser(String ID_, String USER_CODE_, String USER_NAME_, String DEPT_NAME_, String POST_NAME_, String ROLE_, String USER_PHONE_, Date USER_BIRTHDAY_, String USER_SEX_, InputStream USER_PHOTO_,Integer USER_PHOTO_LENGTH_);

    @Override
    public int insertUser(String ID_, String USER_CODE_, String USER_NAME_, String DEPT_NAME_, String POST_NAME_, String ROLE_, String USER_PHONE_, Date USER_BIRTHDAY_, String USER_SEX_, InputStream USER_PHOTO_, Integer USER_PHOTO_LENGTH_) {
        String sql = "insert into v_employee (ID_, USER_CODE_, USER_NAME_, DEPT_NAME_, POST_NAME_, ROLE_, USER_PHONE_,  USER_BIRTHDAY_, USER_SEX_, USER_PHOTO_, USER_PHOTO_LENGTH_) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        return qxJdbcTemplate.update(sql, new Object[]{ID_, USER_CODE_, USER_NAME_, DEPT_NAME_, POST_NAME_, ROLE_, USER_PHONE_, USER_BIRTHDAY_, USER_SEX_, new SqlLobValue(USER_PHOTO_, USER_PHOTO_LENGTH_, new DefaultLobHandler()), USER_PHOTO_LENGTH_}, new int[]{Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,  Types.DATE, Types.VARCHAR, Types.BLOB, Types.INTEGER});
    }



你可能感兴趣的:(vue.js,vue.js,spring,boot,elementui)