springboot后端加vue前端上传文件
时间: 2025-03-08 12:08:20 浏览: 119
### 文件上传功能的技术架构
为了实现文件上传功能,采用Spring Boot作为后端框架负责处理业务逻辑和数据存储;Vue.js则用于构建用户界面并管理前端交互流程。两者通过RESTful API接口相互通信,在确保高效的同时也保障了系统的可维护性和扩展性[^1]。
### 后端开发要点
在Spring Boot项目中创建控制器来接收来自客户端的文件流请求,并对其进行解析保存至服务器指定位置或者云储存服务上。为了避免跨源资源共享(CORS)带来的麻烦,可以利用`@CrossOrigin`注解简化设置过程[^2]:
```java
@RestController
@RequestMapping("/api/files")
public class FileUploadController {
private static final long MAX_FILE_SIZE = 5 * 1024 * 1024;
@PostMapping("/upload")
@CrossOrigin(origins = "*")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file){
if(file.isEmpty()){
return new ResponseEntity<>("Please select a file!", HttpStatus.BAD_REQUEST);
}
try {
// Check file size limit
if (file.getSize() > MAX_FILE_SIZE) {
throw new Exception("File too large!");
}
// Save the file to local or cloud storage here
return new ResponseEntity<>("You successfully uploaded " + file.getOriginalFilename(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.EXPECTATION_FAILED);
}
}
}
```
需要注意的是,默认情况下Spring Boot允许的最大单个文件大小为1MB,如果需要调整这一限制,则可以在`application.properties`文件里修改相应属性值[^3]:
```properties
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
```
### 前端设计思路
对于Vue部分而言,主要任务是从界面上获取用户的输入(即待上传的文件),并通过AJAX方式发送给后台API完成实际的数据传输工作。这里推荐使用axios库来进行异步HTTP请求操作,因为它支持FormData对象从而能够方便地携带二进制资料一同提交。
下面给出一段简单的HTML+JavaScript代码片段展示如何捕获文件选择事件并将选中的资源传送给远程地址:
```html
<template>
<div id="app">
<input type="file" name="avatar" ref="fileInput"/>
<button v-on:click="submit">Submit</button>
</div>
</template>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el:'#app',
methods:{
submit(){
let formData=new FormData();
formData.append('file',this.$refs.fileInput.files[0]);
axios.post('/api/files/upload',formData,{
headers:{'Content-Type':'multipart/form-data'}
}).then(function(response){
console.log(response.data);
}).catch(function(error){
console.error(error.response ? error.response : error.message);
});
}
}
});
</script>
```
阅读全文
相关推荐
















