SpringBoot+vue实现文件上传

话不多说,直接上代码:

vue前端:

<template>
<el-upload style="display: inline;"
           class="upload-ckd"
           ref="upload"
           action="doUpload"
           :limit="1"
           :before-upload="beforeUpload">
  <el-button slot="trigger" type="primary" style="margin-left: 10px;">上传</el-button>
</el-upload>
</template>
<script>
beforeUpload(file){
  if(isEmpty(file.name)){
    this.$message.warning('请选择要上传的文件!')
    return false
  }
  this.files = file;
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const extension3 = file.name.split('.')[1] === 'XLS'
  const extension4 = file.name.split('.')[1] === 'XLSX'
  const isMt10M = file.size / 1024 / 1024 >10
  if (!extension && !extension2 && !extension3 && !extension4) {
    this.$message.warning('上传模板只能是 xls、xlsx格式!')
    return
  }
  if (isMt10M) {
    this.$message.warning('上传模板大小不能超过 10MB!')
    return
  }
  this.fileName = file.name;
  setTimeout(() => {
    this.submitUpload();
  },500);
  return false // 返回false不会自动上传
},
submitUpload() {
  let fileFormData = new FormData();
  fileFormData.append('file', this.files, this.fileName);//filename是键,file是值,就是要传的文件,test.zip是要传的文件名
  this.commonPost({
    url: HMD_UPLOADCKD,
    params: fileFormData,
    requestBody: true
  }).then((data) =>{
    if(data){
      this.$message.success("上传成功");
      this.loadData();
    }
  },(error) => {
    console.log(error);
    this.$message.error("上传失败");
    this.loadData();
  })
}
<script>

后端:

注意点:

1、springBoot的配置文件添加:

spring.servlet.multipart.max-file-size=10Mb
spring.servlet.multipart.max-request-size=-1
@PostMapping (value = "ckd/uploadCkdExecl")
public Object uploadCkdExecl(@RequestParam("file") MultipartFile file, HttpServletRequest request)throws Exception {
    if (file.isEmpty()) {
        throw new BusinessException("上传文件不能为空");
    }
    String fileName=file.getOriginalFilename().toLowerCase();
    if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
        throw new BusinessException("请上传Excel文件");
    }
    //操作人
    String operator=request.getAttribute(StrUtil.USER_WORKNUMBER).toString();
    xxxService.saveUploadCkdExecl(file,operator);
    return true;
}

 

3、附:备份文件:

/**
 * 备份上传文件
 * 
 * @param file
 *            文件
 *            文件名
 * @param BackFilePath
 *            文件备份路径
 * @return 返回备份文件名
 */
public static String backImportFile(MultipartFile file, String BackFilePath)throws Exception{
    StringBuilder sb = new StringBuilder();
    try {
        sb.append(BackFilePath).append("/").append(TimeUtil.getCurTimeToFormat("yyyyMMdd"));
        //判断路径是否存在,不存在则创建
        if (!Files.isWritable(Paths.get(sb.toString()))) {
            try {
                Files.createDirectories(Paths.get(sb.toString()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        sb.append("/")
                .append(TimeUtil.getCurTimeToFormat("HHmmss"))
                .append("-")
                .append(file.getOriginalFilename());

        byte[] bytes = file.getBytes();
        Path path = Paths.get(sb.toString());
        //文件写入指定路径
        Files.write(path, bytes);
    } catch (IOException e) {
        throw new Exception("备份文件失败");
    }
    return sb.toString().substring(sb.toString().lastIndexOf("/")+1);
}
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值