Springboot+vue实现文件的下载和上传

本文详细介绍了如何在Springboot后端和Vue前端配合下,实现文件的上传和下载功能,包括后端的依赖配置、Controller代码和前端的axios使用方法。
摘要由CSDN通过智能技术生成

    概述:要在Springboot和Vue中实现文件的下载和上传,你需要分别在后端和前端进行操作。以下是具体的实现步骤:

1、后端(Springboot):

首先,需要在pom.xml中添加依赖:

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

然后,创建一个控制器类,如FileController.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.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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;
import java.nio.file.StandardCopyOption;

@RestController
public class FileController {

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

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (!Files.exists(fileStoragePath)) {
                Files.createDirectories(fileStoragePath);
            }

            Path targetLocation = fileStoragePath.resolve(file.getOriginalFilename());
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return ResponseEntity.ok("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("文件上传失败");
        }
    }

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

2、前端(Vue):

首先,安装axios库:

npm install axios --save

然后,在Vue组件中添加以下代码:

<template>
  <div>
    <input type="file" @change="uploadFile">
    <button @click="downloadFile">下载文件</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  methods: {
    async uploadFile(event) {
      const file = event.target.files[0];
      const formData = new FormData();
      formData.append('file', file);

      try {
        await axios.post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        alert('文件上传成功');
      } catch (error) {
        alert('文件上传失败');
      }
    },
    async downloadFile() {
      try {
        const response = await axios.get('/download', {
          params: { filename: 'example.txt' },
          responseType: 'blob'
        });
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'example.txt');
        document.body.appendChild(link);
        link.click();
      } catch (error) {
        alert('文件下载失败');
      }
    }
  }
};
</script>
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
由于您没有给出具体的需求,以下是一个基本的文件上传下载的示例代码: 后端代码(基于Spring Boot): ``` @RestController public class FileController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { String filename = file.getOriginalFilename(); byte[] bytes = file.getBytes(); Path path = Paths.get("upload/" + filename); Files.write(path, bytes); return "File uploaded successfully!"; } catch (IOException e) { e.printStackTrace(); return "File upload failed!"; } } @GetMapping("/download/{filename:.+}") public ResponseEntity<Resource> downloadFile(@PathVariable String filename) { try { Path path = Paths.get("upload/" + filename); Resource resource = new UrlResource(path.toUri()); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } catch (MalformedURLException e) { e.printStackTrace(); return ResponseEntity.notFound().build(); } } } ``` 前端代码(基于Vue.js): ``` <template> <div> <h2>File Upload and Download</h2> <input type="file" ref="file" @change="handleFileChange"> <button @click="uploadFile">Upload File</button> <hr> <ul> <li v-for="file in files"> {{file}} <button @click="downloadFile(file)">Download</button> </li> </ul> </div> </template> <script> export default { data() { return { file: null, files: [], }; }, methods: { handleFileChange(event) { this.file = event.target.files[0]; }, uploadFile() { let formData = new FormData(); formData.append("file", this.file); axios.post("/upload", formData).then((response) => { console.log(response.data); }); }, downloadFile(filename) { axios({ url: "/download/" + filename, method: "GET", responseType: "blob", }).then((response) => { 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(); }); }, }, created() { axios.get("/list-files").then((response) => { this.files = response.data; }); }, }; </script> ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nanshaws

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值