Vue+springmvc+mybatis前后端分离学习---(小功能)前端文件上传与后端接收保存记录

记录项目运用的小功能:文件上传与保存

前端的文件上传控件使用ElementUI的【手动上传】,后端使用MultipartFile进行处理,本次先不管具体细节的设置,跑通第一位。
一、前端系统代码:
1.控件:只为跑通就先修改action属性,其中的api将被替换为后端系统端口号,替换与跨域具体请看本记录的第三章。
<el-upload
                class="upload-demo"
                ref="upload"
                action="/api/CCLX_war_exploded/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :file-list="fileList"
                :auto-upload="false"
              >
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button
                  style="margin-left: 10px;"
                  size="small"
                  type="success"
                  @click="submitUpload"
                >上传到服务器</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
              </el-upload>
2.属性与方法:
data() {
    return {
      fileList: [{name: 'xxx.jpg', url: '你的图片路径'}]
    };
  },
methods: {
    submitUpload() {
        this.$refs.upload.submit();
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      }
  },
};
二、后端系统代码:
1.controller方法(每一步请见注释):
 // 处理文件上传
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {

        //获取文件名
        String fileName = multipartFile.getOriginalFilename();

        //获取文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());

        //生成随机文件名
        String localFileName = System.currentTimeMillis() + fileSuffix;

        //设置文件存储路径
        String filePath = "D://uploadtest" + File.separator + localFileName;

        //所上传的文件路径
        File localFile = new File(filePath);

        //存放图片的目录
        File imagePath = new File("D://uploadtest");
        if (!imagePath.exists()) {
            imagePath.mkdirs();
        }

        //转存
        multipartFile.transferTo(localFile);
        return localFileName;
    }
2.踩坑:到这运行会报MultipartFile相关的错误,查半天都说什么Linux系统自动删除临时文件造成的,但明明是Windox系统,最后发现原因在于spring的配置文件中少了以下配置,比如我的是applicationContext.xml,需添加:
<!-- 文件处理-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
效果展示:
1.前台选择图片并上传

在这里插入图片描述

2.前往后台设置的D://uploadtxt查看:

在这里插入图片描述

记录结束 2020-07-29

“没什么难的,不要忘记呼吸”

第一章传送—>Spring与Mybatis单独配置运行记录
第二章传送—>Spring与Mybatis整合思路记录
第三章传送门—>前端搭建与跨域解决

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值