Vue+SpringBoot实现前后端分离的文件上传

1.maven的pom配置如下

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!--加入web模块-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.39</version>
    </dependency>
</dependencies>

2.接下来编写上传的API接口

记得这个要配置下哦!~!!!!!

接着是java代码啦 

@RestController
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {
    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;
    private Logger logger = LoggerFactory.getLogger(UploadController.class);

    @PostMapping("/singlefile")
    public Object singleFileUpload(MultipartFile file) {
        logger.debug("传入的文件参数:{}", JSON.toJSONString(file, true));
        if (Objects.isNull(file) || file.isEmpty()) {
            logger.error("文件为空");
            return "文件为空,请重新上传";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
            //如果没有files文件夹,则创建
            if (!Files.isWritable(path)) {
                Files.createDirectories(Paths.get(UPLOAD_FOLDER));
            }
            //文件写入指定路径
            Files.write(path, bytes);
            logger.debug("文件写入成功...");
            return "文件上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "后端异常...";
        }
    }
}

CrossOrigin注解:解决跨域问题,因为前后端完全分离,跨域问题在所难免,加上这个注解会让Controller支持跨域,如果去掉这个注解,前端Ajax请求不会到后端。这只是跨域的一种解决方法,还有其他解决方法这篇文章先不涉及。
MultipartFile:SpringMVC的multipartFile对象,用于接收前端请求传入的FormData。
PostMapping是Spring4.3以后引入的新注解,是为了简化HTTP方法的映射,相当于我们常用的@RequestMapping(value = “/xx”, method = RequestMethod.POST).
后端至此已经做完了,很简单。

 

前端vue代码

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <form>
      <input type="file" @change="getFile($event)">
      <button class="button button-primary button-pill button-small" @click="submit($event)">提交</button>
    </form>
  </div>
</template>

<script>
  import axios from 'axios';

  export default {
    name: 'HelloWorld',
    data() {
      return {
        msg: 'Welcome to Your Vue.js App',
        file: ''
      }
    },
    methods: {
      getFile: function (event) {
        this.file = event.target.files[0];
        console.log(this.file);
      },
      submit: function (event) {
        //阻止元素发生默认的行为
        event.preventDefault();
        let formData = new FormData();
        formData.append("file", this.file);
        axios.post('http://localhost:8082/upload/singlefile', formData)
          .then(function (response) {
            alert(response.data);
            console.log(response);
            window.location.reload();
          })
          .catch(function (error) {
            alert("上传失败");
            console.log(error);
            window.location.reload();
          });
      }
    }
  }
</script>


 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
课程的实战源码是我在 GitHub 上开源项目 spring-boot-projects 中的其中一个项目代码,目前已有 2300 多个 star,项目截图如下: 由于项目比较受大家欢迎,因此心中就出现了将它做成教学视频的想法,也就是你现在了解的这个课程《SpringBoot入门及前后端分离项目开发》,本课程是一个 Spring Boot 技术栈的实战类课程,课程共分为 3 大部分,前面两个部分为基础环境准备和相关概念介绍,第三个部分是 Spring Boot 项目实践开发。Spring Boot 介绍、前后端分离、API 规范等内容旨在让读者更加熟悉 SpringBoot 及企业开发中需要注意的事项并具有使用 SpringBoot 技术进行基本功能开发的能力;这最后的项目实战为课程的主要部分,我会带着大家实际的开发一个前后端分离的 Spring Boot 实践项目,让大家实际操作并从无到有开发一个线上项目,并学习到一定的开发经验以及其中的开发技巧,旨在让读者具有将 Spring Boot 真正应用于项目开发的能力; 以下为实践项目的页面和功能展示,分别为:登录页面 列表页面(分页功能) 图片上传功能 富文本编辑器整合使用 实践项目的主要功能和页面就是这些,通过项目展示大家也能够感受到,在实际应用开发中的高频次功能都已经实现,稍加修改就可以运用到企业开发中,整个项目的开发模式为前后端分离的模式,即 Spring Boot 提供后端接口,前端页面通过 Ajax 异步调用接口的方式与后端服务器进行交互并将数据填充至页面中,这也是目前企业开发中比较重用的开发模式,希望大家能够了解并且能够实际的上手开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值