概述:要在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>