Springboot实现简单的文件上传
时间: 2023-06-17 11:07:29 浏览: 55
在Springboot中,可以使用MultipartFile类来实现文件上传。下面是一个简单的示例:
1. 在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2. 创建一个上传文件的Controller,示例如下:
```java
@RestController
@RequestMapping("/file")
public class FileController {
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
try {
// 文件保存
String fileName = file.getOriginalFilename();
String filePath = "D:/upload/";
File dest = new File(filePath + fileName);
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
}
```
3. 创建一个简单的页面用于上传文件:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<button type="submit">提交</button>
</form>
</body>
</html>
```
4. 运行Springboot应用,访问http://localhost:8080即可看到文件上传页面。选择要上传的文件,并提交表单,即可将文件上传到指定目录。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)