帮我写个springboot+vue 图片上传
时间: 2023-07-25 21:47:58 浏览: 57
好的,以下是一个简单的Spring Boot和Vue.js的图片上传示例:
1. 创建Spring Boot项目
首先,我们需要创建一个Spring Boot项目。可以使用Spring Initializr或者其他方式创建一个基础的Spring Boot项目。
2. 添加依赖
在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
```
3. 编写后端代码
创建一个Controller类,处理上传请求:
```java
@RestController
public class UploadController {
private static final String UPLOAD_DIR = "/path/to/upload/dir";
@PostMapping("/upload")
public String upload(MultipartFile file) throws IOException {
// 生成唯一文件名
String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
// 将文件保存到指定目录
File targetFile = new File(UPLOAD_DIR, fileName);
FileUtils.copyInputStreamToFile(file.getInputStream(), targetFile);
// 返回文件URL
return "/uploads/" + fileName;
}
}
```
4. 创建Vue.js项目
在命令行中执行以下命令创建一个Vue.js项目:
```bash
vue create my-project
```
5. 添加依赖
在package.json中添加以下依赖:
```json
"devDependencies": {
"axios": "^0.21.1"
}
```
6. 编写前端代码
创建一个组件,处理文件上传:
```html
<template>
<div>
<input type="file" @change="handleFileChange">
<button @click="uploadFile">上传</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
file: null
}
},
methods: {
handleFileChange(event) {
this.file = event.target.files[0]
},
uploadFile() {
let formData = new FormData()
formData.append('file', this.file)
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log(response.data)
}).catch(error => {
console.error(error)
})
}
}
}
</script>
```
这个组件包含一个文件选择器和一个上传按钮。当用户选择文件后,文件会被保存到组件的data中。当用户点击上传按钮时,组件使用axios库向后端发送一个POST请求,上传文件。
注意:这个示例中的上传路径为“/upload”,需要根据实际情况修改。
以上就是一个简单的Spring Boot和Vue.js的图片上传示例,你可以根据自己的需求进行修改和扩展。