springboot上传pdf文件
时间: 2023-08-29 21:12:22 浏览: 54
你可以使用Spring Boot的MultipartResolver来处理文件上传。
首先,添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
```
然后,在你的Controller中添加一个方法来处理文件上传:
```java
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
// 检查文件是否为空
if (file.isEmpty()) {
return "上传的文件为空";
}
// 检查文件类型
if (!"application/pdf".equals(file.getContentType())) {
return "上传的文件必须是PDF类型";
}
// 保存文件
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("/path/to/your/upload/folder/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
return "文件上传失败";
}
return "文件上传成功";
}
```
在这个例子中,我们检查了文件是否为空,文件类型是否为PDF,并把文件保存到指定的路径中。
最后,在你的HTML表单中添加一个文件上传控件:
```html
<form method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<button type="submit">上传文件</button>
</form>
```
当用户提交表单时,文件将被上传到你的Controller中的uploadFile方法中进行处理。