springboot+vue实现文件上传代码
时间: 2024-06-17 10:05:30 浏览: 136
可以的,实现文件上传的代码如下所示:
SpringBoot后端实现:
```java
@RestController
@RequestMapping("/api")
public class FileController {
@Value("${file.upload.path}")
private String filePath;
@PostMapping("/upload")
public String uploadFile(MultipartFile file) throws IOException {
// 获取文件名
String fileName = file.getOriginalFilename();
// 构建文件路径
String path = filePath + fileName;
// 保存文件到本地
file.transferTo(new File(path));
return "上传成功!";
}
}
```
Vue前端实现:
```vue
<template>
<div class="upload">
<input type="file" ref="file" @change="uploadFile">
</div>
</template>
<script>
export default {
methods: {
uploadFile() {
let formData = new FormData();
formData.append('file', this.$refs.file.files);
this.$http.post('/api/upload', formData)
.then(res => {
console.log(res.data);
})
.catch(err => {
console.error(err);
});
}
}
}
</script>
```
需要注意的是,后端的文件上传路径需要在配置文件中配置,如下所示:
```properties
file.upload.path=/data/upload/
```
另外,这里使用了axios库来发送请求,需要在Vue中安装并引入axios库。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)