spring boot vue upload file
时间: 2023-12-02 09:04:22 浏览: 115
在 Spring Boot 和 Vue 中实现文件上传,可以按照以下步骤进行:
1. 在 Vue 中创建一个文件上传表单,代码如下:
```
<template>
<div>
<form>
<input type="file" ref="fileInput">
<button type="button" @click="uploadFile">上传</button>
</form>
</div>
</template>
<script>
export default {
methods: {
uploadFile() {
let file = this.$refs.fileInput.files[0];
let formData = new FormData();
formData.append("file", file);
// 发送文件到后端
}
}
}
</script>
```
2. 在 Spring Boot 中创建一个文件上传接口,代码如下:
```
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
try {
String fileName = file.getOriginalFilename();
Path path = Paths.get("/uploads/" + fileName);
Files.write(path, file.getBytes());
return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>("Failed to upload file", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
```
3. 在 Vue 中使用 `axios` 发送文件到后端,代码如下:
```
<template>
<div>
<form>
<input type="file" ref="fileInput">
<button type="button" @click="uploadFile">上传</button>
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
methods: {
uploadFile() {
let file = this.$refs.fileInput.files[0];
let formData = new FormData();
formData.append("file", file);
axios.post("/upload", formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log(response.data);
}).catch(error => {
console.log(error);
});
}
}
}
</script>
```
以上就是在 Spring Boot 和 Vue 中实现文件上传的步骤。注意,在 Spring Boot 中需要在 `application.properties` 中配置文件上传路径,例如:
```
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=200MB
spring.servlet.multipart.max-request-size=215MB
spring.servlet.multipart.location=/uploads/
```
阅读全文