springboot vue前后端分离文件
时间: 2025-05-16 09:57:43 浏览: 12
### SpringBoot 和 Vue 实现前后端分离时的文件上传与下载
#### 文件上传功能
在基于 Spring Boot 的后端服务中,可以使用 `MultipartFile` 来接收前端传递过来的文件数据。以下是具体的实现方式:
1. **后端接口定义**
定义一个用于处理文件上传的 RESTful 接口,通过 `@RequestParam` 注解绑定上传的文件对象。
```java
@RestController
public class FileController {
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return new ResponseEntity<>("Please select a file to upload", HttpStatus.BAD_REQUEST);
}
try {
// 获取原始文件名并保存到指定路径
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
Path path = Paths.get(UPLOAD_DIR + File.separator + fileName); // UPLOAD_DIR 是存储文件的目标目录
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
return new ResponseEntity<>("You successfully uploaded " + fileName, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
```
2. **前端部分(Vue.js)**
使用 Axios 库发送 POST 请求并将文件作为 FormData 对象的一部分提交给服务器。
```javascript
methods: {
handleUpload(event) {
const formData = new FormData();
formData.append('file', event.target.files[0]);
axios.post('/api/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error.response ? error.response.data : error.message);
});
}
}
```
---
#### 文件下载功能
对于文件下载操作,通常会返回流形式的数据供客户端解析成实际文件。
1. **后端接口设计**
创建一个新的 API 路由来提供文件下载的服务逻辑。
```java
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws IOException {
Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize(); // 构建完整的文件路径
Resource resource = new UrlResource(filePath.toUri());
if (!resource.exists() || !resource.isReadable()) {
throw new RuntimeException("Could not read the file!");
}
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + URLEncoder.encode(resource.getFilename(), "UTF-8"));
return ResponseEntity.ok()
.headers(header)
.contentLength(resource.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
```
2. **前端调用方法**
下载请求可以通过创建隐藏表单或者直接触发浏览器行为完成。
```javascript
methods: {
triggerDownload(filename) {
window.location.href = `/api/download/${encodeURIComponent(filename)}`;
}
}
```
---
#### 注意事项
- 确保配置好跨域支持以便于前后端能够正常通信[^1]。
- 需要设置合理的权限控制机制防止未授权访问敏感资源[^2]。
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 如果涉及图片预览等功能可能还需要额外依赖 -->
<dependency>
<groupId>com.github.tsulik</groupId>
<artifactId>jimp-core</artifactId>
<version>0.9.7</version>
</dependency>
```
阅读全文
相关推荐


















