springboot + vue3 + ts 头像上传
时间: 2025-01-03 21:39:40 浏览: 41
### 实现用户头像上传功能
#### 后端部分:Spring Boot配置
为了支持文件上传,在`pom.xml`中添加必要的依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 文件上传所需 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
```
创建控制器处理文件上传请求。定义一个接收multipart/form-data类型的POST请求的方法来保存图片到服务器指定位置[^1]。
```java
@RestController
@RequestMapping("/api/avatar")
public class AvatarController {
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 处理文件存储逻辑...
return new ResponseEntity<>("{'message':'Upload successful'}", HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.EXPECTATION_FAILED);
}
}
}
```
#### 前端部分:Vue 3 + TypeScript实现
在Vue组件内编写用于选择并提交图像给后端的服务方法。这里假设已经完成基本的Vue CLI项目搭建工作[^3]。
首先安装axios以便于发起HTTP请求:
```bash
npm install axios
```
接着修改`.vue`文件,加入表单元素让用户可以选择本地图片,并通过事件触发器调用服务发送数据至后台API接口[^2]:
```typescript
<script lang="ts">
import { defineComponent, ref } from 'vue';
import axios from 'axios';
export default defineComponent({
name: "AvatarUploader",
setup() {
const selectedImage = ref<File | null>(null);
function handleFileChange(event:Event){
const target = event.target as HTMLInputElement;
if(target.files?.length){
selectedImage.value=target.files[0];
}
}
async function handleSubmit(){
if(!selectedImage.value){return;}
let formData=new FormData();
formData.append('file',selectedImage.value);
await axios.post('/api/avatar/upload',
formData,
{
headers:{
'Content-Type': 'multipart/form-data'
}
}).then((response)=>{
console.log(response.data.message);
});
}
return{
handleFileChange,
handleSubmit
};
},
});
</script>
<template>
<div>
<input type="file" accept=".jpg,.jpeg,.png" @change="handleFileChange"/>
<button @click="handleSubmit">Submit</button>
</div>
</template>
```
阅读全文
相关推荐
















