java(springboot)+elementui实现多文件上传到本地服务器

java(springboot)+elementui实现多文件上传到本地服务器

垃圾代码,自行理解

1 java

1.1 yml配置(properties同)

max-xxx-xxx设置文件最大接受值

# Spring
spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 200MB
      max-request-size: 200MB

1.2 controller

MultipartFile为文件,其他表单信息以Json格式发送过来

    @PostMapping("/addContract")
    public AjaxResult addContract(@RequestParam("files") List<MultipartFile> files, @RequestParam("fileNames") List multipartFileNames,
                                @RequestParam("erpContract") Object obj ){
        String contractId = erpContractService.insertErpContract(obj, files, multipartFileNames);
        //返回插入合同的合同编号
        return  AjaxResult.success(contractId);
    }

1.3 service

public String insertErpContract(Object obj,List<MultipartFile> files, List multipartFileNames);

1.4 serviceImpl

t跳到====>erpContractFileService.insertErpContractFile(erpContract,files,multipartFileNames);

 /**
     * 新增合同信息
     *
     * @param obj 合同信息
     * @return contractId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertErpContract(Object obj,List<MultipartFile> files, List multipartFileNames) {
        JSONObject jsonObject = JSONObject.parseObject(obj.toString());
        ErpContract erpContract = BeanUtil.toBean(jsonObject, ErpContract.class);
        //首次插入 生成合同号
        String contractId = this.generateContractNumber(erpContract);
        erpContract.setContractId(contractId);
        erpContract.setCreateUser(SecurityUtils.getUsername());
        erpContract.setCreateTime(DateUtils.getNowDate());
        erpContract.setDeleteFlag(0L);
        erpContractMapper.insertErpContract(erpContract);
        //添加后返回合同编号id
        //传入的是erpContract 而不是erpContractFile哈
        erpContractFileService.insertErpContractFile(erpContract,files,multipartFileNames);
        //发票信息和支付信息单独添加
        return contractId;
    }
 @Service
public class ErpContractFileServiceImpl implements IErpContractFileService {
    @Autowired
    private ErpContractFileMapper erpContractFileMapper;
    /** 省略  */
    
     @Override
    public void insertErpContractFile(ErpContract erpContract, List<MultipartFile> files, List multipartFileNames) {
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);//获取文件
            Object fileName = multipartFileNames.get(i);//获取源文件名
            String newFileName = fileName.toString();//把文件名类型转换为String类型
            String contractName = erpContract.getContractName();
            //处理并保存文件到本地 handleFileAndSave
            //将文件存进硬盘中
            String filePath = this.saveFile(file, newFileName, contractName);
            //传入contractId,fileName,filePath传入ErpContractFile实体类
            ErpContractFile erpContractFile = new ErpContractFile();

            erpContractFile.setContractId(erpContract.getContractId());
            erpContractFile.setFilePath(filePath);
            erpContractFile.setUploadTime(DateUtils.getNowDate());
            erpContractFile.setUploadUser(SecurityUtils.getUsername());
            erpContractFile.setDeleteFlag(0);
            erpContractFileMapper.insertErpContractFile(erpContractFile);
        }
    }
    @Override
    public String saveFile(MultipartFile file, String newFileName, String contractName) 	{
        return MyFileUtils.uploadFile(file, newFileName, contractName);
    }
}

1.5 流

保存文件到服务器硬盘

public class MyFileUtils { 
    /**省略*/
    
    public static String uploadFile(MultipartFile file, String newFileName, String contractName) {
        String pathName = "";
        File dir = new File("D:\\erpContract\\"+contractName);
        //文件夹不存在便创建文件夹,文件夹存在便不创建
        if( !dir.exists()&&!dir.isDirectory() ) dir.mkdirs();
        //传进来的参数没起作用,
        pathName = dir+"\\" + newFileName;//将存储地址与文件名拼接在一起
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pathName);
            fos.write(file.getBytes());//写入文件
            return pathName;
        } catch (Exception e) {
            e.printStackTrace();
            return pathName;
        } finally {
            try {
                fos.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

1.6 mapper

保存文件路径到数据库

<insert id="insertErpContractFile" useGeneratedKeys = "true"  keyProperty = "id" parameterType="com.xxx.erp.contract.domain.ErpContractFile">
        insert into erp_contract_file
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">id,</if>
            <if test="contractId != null and contractId != ''">contract_id,</if>
            <if test="filePath != null and filePath!=''">file_path,</if>
            <if test="uploadUser != null and uploadUser!=''">upload_user,</if>
            <if test="uploadTime != null">upload_time,</if>
            <if test="deleteFlag != null">delete_flag,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">#{id},</if>
            <if test="contractId != null and contractId != ''">#{contractId},</if>
            <if test="filePath != null and filePath!=''">#{filePath},</if>
            <if test="uploadUser != null and uploadUser!=''">#{uploadUser},</if>
            <if test="uploadTime != null">#{uploadTime},</if>
            <if test="deleteFlag != null">#{deleteFlag},</if>
        </trim>
    </insert>

2 vue 前端

2.1 vue

<el-form ref="form" :model="form" :rules="rules"  :inline="true" label-width="150px" >
    <!--省略-->
	<el-col >
    	<el-upload
            class="upload-demo"
            action="http://xxxx/xxxx/xxxx/xxxxx"
            ref="upload"
            enctype="multipart/form-data"
            :http-request="httpRequest"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="onChangeFile"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :auto-upload="false"
            multiple
            :file-list="fileList">
            <el-form-item label="合同附件" >
              <el-button  type="primary"  align="center">上传附件<i class="el-icon-upload el-icon--right"></i></el-button>
            </el-form-item>
		</el-upload>
    </el-col>
 </el-form>
<div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPay">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
</div>


2.2 js提交表单

submitForm(file) {
      if(this.form.contractId){
        this.$alert('不可在本合同下再新建合同,您可以添加新的支付信息或者发票信息', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: `action: ${ action }`
            });
          }
        })
      }else{
        let { uploadFiles } = this.$refs.upload
        let param = new FormData()
        // 在这里对每一张图片进行大小的校验,如果不符合则提示,所有不符合的都提示,校验完成后只要有不符合条件的就不执行下面的操作
        uploadFiles.forEach(item => {
          param.append("files", item.raw);
          param.append("fileNames", item.name);
        })
        param.append("erpContract", JSON.stringify(this.form));
        /** 上传的参数有fileName,file,projectsAddBo表单参数-添加项目的信息*/
        addContract(param).then(response => {
          //应该返回一个id,然后赋值给form.id
          this.form.contractId = response.msg;
          this.open = false;
          this.$alert('新增成功', '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'success',
                message: `action: ${ action }`
              });
            }
          });
          this.getList();
          this.$router.push({ path: '/xxxx/xxxx'});
        })
      }//else
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现文件上传需要完成以下几个步骤: 1. 在前端页面添加上传文件的表单,并绑定上传事件,将文件上传到后端。 2. 在后端接收前端上传的文件,并保存到服务器上。 下面是一个简单的示例,演示如何使用 Spring Boot + Vue.js + ElementUI 实现文件上传的功能。 前端代码: ```html <template> <div> <el-upload class="upload-demo" ref="upload" :action="uploadUrl" :on-success="handleSuccess" :before-upload="beforeUpload" :file-list="fileList"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </div> </template> <script> export default { data() { return { uploadUrl: "/upload", fileList: [] }; }, methods: { // 上传前的钩子函数 beforeUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error("上传头像图片只能是 JPG/PNG 格式!"); } if (!isLt500K) { this.$message.error("上传头像图片大小不能超过 500KB!"); } return isJPG && isLt500K; }, // 上传成功的回调函数 handleSuccess(response, file, fileList) { this.fileList = fileList; this.$emit("upload-success", response); } } }; </script> ``` 在上面的代码中,我们使用了 ElementUI 的 Upload 组件,将上传文件的表单渲染到页面上。同时,我们还绑定了 beforeUpload 和 handleSuccess 两个事件,用于上传前的校验和上传成功后的回调。 注意:在使用 beforeUpload 钩子函数时,需要返回一个布尔值,表示是否允许上传。如果返回 false,上传将会被终止。 后端代码: ```java @RestController public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception { if (file.isEmpty()) { return "上传文件为空!"; } // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 设置文件存储路径 String filePath = "/tmp/"; // 重新生成文件名 fileName = UUID.randomUUID() + suffixName; // 创建文件对象 File dest = new File(filePath + fileName); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } // 保存文件 file.transferTo(dest); return "文件上传成功!"; } } ``` 在上面的代码中,我们使用了 Spring Boot 的 @PostMapping 注解,将上传文件的接口地址映射到 /upload 路径上。同时,我们还使用了 MultipartFile 类型的参数来接收前端上传的文件。 在接收到文件后,我们首先判断文件是否为空。如果不为空,我们通过 MultipartFile 类型的方法获取文件名和后缀名,并将文件存储到指定的路径下。最后,我们返回一个字符串,表示上传成功。 需要注意的是,在保存文件时,我们使用了 transferTo 方法。该方法会将上传文件保存到指定的路径下,并自动关闭文件流。同时,我们还判断了目录是否存在,如果不存在,就创建一个新的目录。 综上所述,通过以上的代码,我们可以实现 Spring Boot + Vue.js + ElementUI文件上传功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值