Spring Boot + Vue 实现文件导入导出功能

文章目录

1、概述

​ 在现代Web应用开发中,文件的导入导出是一个常见的需求。Spring Boot作为后端开发的强大框架,搭配前端框架Vue,可以轻松实现这一功能。本文将介绍如何使用Spring Boot和Vue来实现文件的导入导出。在本方案中,Spring Boot将作为后端服务来处理文件的存储和读取逻辑,而Vue将作为前端界面与用户进行交互。我们将使用Spring Boot的MultipartFile来接收前端上传的文件,并使用ResponseEntity来将文件发送给前端用户进行下载。

2、后端实现(Spring Boot)

环境搭建

首先,确保你已经安装了Java开发环境和Maven或Gradle。然后,创建一个新的Spring Boot项目,并添加以下依赖到pom.xmlbuild.gradle文件中:

xml 复制代码
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

文件上传接口

创建一个FileController来处理文件上传请求。这里我们使用MultipartFile来接收上传的文件,并将其保存到服务器的指定目录:

java 复制代码
@RestController
public class FileController {

    private static final String UPLOADED_FOLDER = "uploaded/";

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("File is empty");
        }

        try {
            String fileName = file.getOriginalFilename();
            Path targetLocation = Paths.get(UPLOADED_FOLDER).resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return ResponseEntity.ok("File uploaded successfully: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file");
        }
    }

    // 其他必要的方法,如文件存储路径配置等
}

文件下载接口

在同一个FileController中,添加一个用于文件下载的方法。这里我们使用FileSystemResource来定位文件,并将其作为HTTP响应的主体发送给客户端:

java 复制代码
@GetMapping("/download/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
    String folder = "uploaded/";
    Path filePath = Paths.get(folder).resolve(filename);
    Resource resource = new FileSystemResource(filePath);

    try {
        if (!resource.exists() || !Files.isReadable(resource.getFile().toPath())) {
            return ResponseEntity.notFound().build();
        }
    } catch (IOException e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Could not read file");
    }

    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
            .body(resource);
}
3、前端实现(Vue)

环境搭建

使用Vue CLI创建一个新的Vue项目,并安装axios用于发送HTTP请求:

bash 复制代码
vue create my-vue-app
cd my-vue-app
vue add axios

文件上传

在Vue组件中,添加一个表单用于文件上传,并使用axios发送请求到后端的文件上传接口。同时,我们添加了文件选择后的事件处理和上传前的预处理:

vue 复制代码
<template>
  <div>
    <h1>File Upload</h1>
    <form @submit.prevent="uploadFile">
      <input type="file" @change="onFileChange" />
      <button type="submit">Upload</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      selectedFile: null,
    };
  },
  methods: {
    onFileChange(event) {
      this.selectedFile = event.target.files[0];
    },
    async uploadFile() {
      if (this.selectedFile) {
        const formData = new FormData();
        formData.append('file', this.selectedFile);
        try {
          const response = await axios.post('/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
            },
          });
          console.log(response.data);
          // 处理上传成功后的逻辑,如更新文件列表等
        } catch (error) {
          console.error(error);
          // 处理上传失败的逻辑
        }
      }
    },
  },
};
</script>

文件下载

在Vue组件中,添加一个链接或按钮,当用户点击时,调用axios发送请求到后端的文件下载接口,并处理响应以触发文件下载:

vue 复制代码
<template>
  <div>
    <!-- ... -->
    <a :href="downloadUrl" download>Download File</a>
    <!-- ... -->
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      downloadUrl: null,
    };
  },
  methods: {
    async downloadFile(filename) {
      const response = await axios({
        method: 'GET',
        url: `/download/${filename}`,
        responseType: 'blob', // 重要
      });

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    },
  },
  watch: {
    // 假设filename是从某个状态或props中获取的文件名
    filename(newFilename) {
      if (newFilename) {
        this.downloadUrl = `/download/${newFilename}`;
      }
    },
  },
};
</script>
4、总结

​ 通过上述步骤,我们详细介绍了如何使用Spring Boot和Vue实现文件的导入导出功能。后端Spring Boot提供了文件上传和下载的RESTful API,而前端Vue则提供了用户友好的界面和交互逻辑。这种前后端分离的架构不仅使得开发过程更加清晰,也提高了应用的可维护性和可扩展性。此外,通过使用axiosFormData,我们能够轻松处理HTTP请求和文件数据的传输,而EasyExcel等库的使用则进一步简化了文件处理的复杂性。

相关推荐
Momo__38 分钟前
Vue 3.6 Vapor Mode:跳过虚拟 DOM,性能极致优化
前端·vue.js
walking9572 小时前
重新学习前端之JavaScript
前端·vue.js·面试
walking9572 小时前
重新学习前端之HTML
前端·vue.js·面试
walking9572 小时前
重新学习前端之Vue
前端·vue.js·面试
泉城老铁2 小时前
springboot实现word转换pdf
vue.js·后端
walking9572 小时前
重新学习前端之Linux
前端·vue.js·面试
walking9572 小时前
重新学习前端之CSS
前端·vue.js·面试
walking9572 小时前
重新学习前端之Git
前端·vue.js·面试
2401_878820472 小时前
Sa-Token基础篇
java·spring boot·后端·sa-token
Hello--_--World3 小时前
Vue指令:v-if vs v-show、v-if 与 v-for 的优先级冲突、自定义指令
前端·javascript·vue.js