前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >使用Spring Boot与Vue.js构建文件管理功能:上传、下载及删除操作详解

使用Spring Boot与Vue.js构建文件管理功能:上传、下载及删除操作详解

原创
作者头像
Front_Yue
发布2024-11-11 18:38:12
发布2024-11-11 18:38:12
30400
代码可运行
举报
运行总次数:0
代码可运行

好文推荐

今日推荐《Spring AI 再更新:如何借助全局参数实现智能数据库操作与个性化待办管理》 这篇文章介绍了基于 Spring AI 的系统优化,不仅为我们提供了一个强大的智能助手框架,也为实际业务中的智能化系统提供了可借鉴的方案,可以基于此进一步扩展功能,打造更加智能化和个性化的业务解决方案。

前言

在现代Web应用中,文件上传、下载和删除功能是非常常见的需求。本文将介绍如何使用Spring Boot作为后端框架,Vue.js作为前端框架,实现本地文件的上传、下载和删除功能。

后端部分:Spring Boot

1. 创建Spring Boot项目

首先,创建一个新的Spring Boot项目,并添加必要的依赖项,如Spring Web和Spring Boot DevTools。

代码语言:xml
复制
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

2. 创建文件上传、下载和删除的Controller

创建一个Controller类来处理文件的上传、下载和删除请求。

代码语言:java
复制
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/files")
public class FileController {

    private final Path rootLocation = Paths.get("uploads");

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
            return ResponseEntity.ok().body("File uploaded successfully: " + file.getOriginalFilename());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Could not upload the file: " + file.getOriginalFilename() + "!");
        }
    }

    @GetMapping("/download/{filename:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
        try {
            Path file = rootLocation.resolve(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @DeleteMapping("/delete/{filename:.+}")
    public ResponseEntity<String> deleteFile(@PathVariable String filename) {
        try {
            Files.delete(rootLocation.resolve(filename));
            return ResponseEntity.ok().body("File deleted successfully: " + filename);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Could not delete the file: " + filename + "!");
        }
    }
}

3. 配置文件存储路径

application.properties文件中配置文件存储路径:

代码语言:properties
复制
file.upload-dir=uploads

前端部分:Vue.js

1. 创建Vue项目

使用Vue CLI创建一个新的Vue项目,并安装必要的依赖项,如axios用于HTTP请求。

代码语言:bash
复制
vue create file-upload-download-delete
cd file-upload-download-delete
npm install axios

2. 创建文件上传、下载和删除的组件

创建一个Vue组件来处理文件的上传、下载和删除操作。

代码语言:vue
复制
<template>
  <div>
    <h2>File Upload</h2>
    <input type="file" @change="handleFileUpload" />
    <button @click="uploadFile">Upload</button>

    <h2>File Download</h2>
    <input type="text" v-model="fileName" placeholder="Enter file name" />
    <button @click="downloadFile">Download</button>

    <h2>File Delete</h2>
    <input type="text" v-model="deleteFileName" placeholder="Enter file name" />
    <button @click="deleteFile">Delete</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      fileName: '',
      deleteFileName: ''
    };
  },
  methods: {
    handleFileUpload(event) {
      this.file = event.target.files[0];
    },
    async uploadFile() {
      const formData = new FormData();
      formData.append('file', this.file);
      try {
        const response = await axios.post('/api/files/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        alert(response.data);
      } catch (error) {
        alert(error.response.data);
      }
    },
    async downloadFile() {
      try {
        const response = await axios.get(`/api/files/download/${this.fileName}`, {
          responseType: 'blob'
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', this.fileName);
        document.body.appendChild(link);
        link.click();
      } catch (error) {
        alert(error.response.data);
      }
    },
    async deleteFile() {
      try {
        const response = await axios.delete(`/api/files/delete/${this.deleteFileName}`);
        alert(response.data);
      } catch (error) {
        alert(error.response.data);
      }
    }
  }
};
</script>

3. 配置Vue Router

配置Vue Router以便访问该组件。

代码语言:javascript
代码运行次数:0
复制
import Vue from 'vue';
import Router from 'vue-router';
import FileComponent from './components/FileComponent.vue';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'FileComponent',
      component: FileComponent
    }
  ]
});

总结

通过本文,我们学习了如何使用Spring Boot和Vue.js实现本地文件的上传、下载和删除功能。后端使用Spring Boot处理文件的存储和操作,前端使用Vue.js提供用户界面和交互。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 后端部分:Spring Boot
    • 1. 创建Spring Boot项目
    • 2. 创建文件上传、下载和删除的Controller
    • 3. 配置文件存储路径
  • 前端部分:Vue.js
    • 1. 创建Vue项目
    • 2. 创建文件上传、下载和删除的组件
    • 3. 配置Vue Router
  • 总结
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档