要在Spring Boot和Vue 3中实现文件上传和下载,您可以按照以下步骤进行操作:

  1. 在Spring Boot中,创建一个文件上传和下载的Controller类。使用@PostMapping注解创建一个POST请求处理方法来处理文件上传。在方法中,使用@RequestParam注解来接收文件,并使用MultipartFile类型来保存文件。然后,使用FileOutputStream将文件保存到本地磁盘或者数据库中。

    @RestController
    public class FileController {
    
        @PostMapping("/upload")
        public String uploadFile(@RequestParam("file") MultipartFile file) {
            // 保存文件到本地磁盘或者数据库
            // ...
            return "File uploaded successfully";
        }
    
        @GetMapping("/download")
        public ResponseEntity<Resource> downloadFile() {
            // 从本地磁盘或者数据库中获取文件
            // ...
            // 创建一个Resource对象来保存文件
            Resource resource = new ByteArrayResource(fileBytes);
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .body(resource);
        }
    }
    
  2. 在Vue 3中,使用el-upload组件来实现文件上传。首先,您需要在Vue 3中安装element-plus,并在需要使用的组件中导入和注册el-upload组件。

    <template>
      <el-upload
        action="/upload"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        :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="upload">上传</el-button>
      </el-upload>
    </template>
    
    <script>
    import { ref } from 'vue';
    
    export default {
      setup() {
        const fileList = ref([]);
    
        const handleSuccess = (response) => {
          console.log(response);
          // 处理上传成功的逻辑
        };
    
        const beforeUpload = (file) => {
          fileList.value.push(file);
          return false; // 阻止自动上传
        };
    
        const upload = () => {
          fileList.value.forEach((file) => {
            const formData = new FormData();
            formData.append('file', file);
    
            // 发起上传请求
            // ...
          });
        };
    
        return {
          fileList,
          handleSuccess,
          beforeUpload,
          upload,
        };
      },
    };
    </script>
    
  3. 在Vue 3中,使用el-link组件来实现文件下载。您可以在需要下载文件的地方使用el-link组件,并将其href属性指向Spring Boot中的下载接口。

    <template>
      <el-link :href="downloadUrl" target="_blank">下载文件</el-link>
    </template>
    
    <script>
    import { ref } from 'vue';
    
    export default {
      setup() {
        const downloadUrl = ref('/download');
    
        return {
          downloadUrl,
        };
      },
    };
    </script>
    

请注意,在上述示例中,我使用了element-plus库来实现UI组件,您可以根据自己的喜好选择其他的UI库。同时,您需要根据实际情况来修改Spring Boot中的文件保存和获取逻辑

Springboot vue3 element-plus 实现文件上传下载

原文地址: https://www.cveoy.top/t/topic/hPsN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录