springboot pdf文件上传预览和下载
时间: 2025-06-02 10:35:12 浏览: 13
### 实现Spring Boot中的PDF文件上传、预览和下载
在Spring Boot应用程序中实现PDF文件的上传、预览和下载是一项常见的需求。以下是详细的解决方案。
#### PDF 文件上传
为了支持PDF文件的上传,可以创建一个控制器来处理`multipart/form-data`请求。通过使用`@RequestParam`注解绑定前端传递的文件对象到后端方法参数中[^1]。
```java
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@RestController
@RequestMapping("/pdf")
public class PdfController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "Failed to upload empty file.";
}
try {
byte[] bytes = file.getBytes();
// 将字节保存至服务器上的指定位置或其他存储方式
Path path = Paths.get("uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
return "You successfully uploaded '" + file.getOriginalFilename() + "'";
} catch (IOException e) {
return "Error occurred while uploading the file!";
}
}
}
```
#### PDF 文件预览
对于PDF文件的预览,可以通过返回HTTP响应头设置为`application/pdf`并流式传输文件内容给客户端[^1]。
```java
@GetMapping("/preview/{filename}")
public ResponseEntity<Resource> previewPdf(@PathVariable String filename) throws IOException {
Path filePath = Paths.get("uploads/" + filename).toAbsolutePath().normalize();
Resource resource = new UrlResource(filePath.toUri());
if (!resource.exists() || !resource.isReadable()) {
throw new RuntimeException("Cannot read the file!");
}
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"");
MediaType mediaType = Files.probeContentType(resource.getFile().toPath()) != null ?
MediaType.parseMediaType(Files.probeContentType(resource.getFile().toPath())) :
MediaType.APPLICATION_OCTET_STREAM;
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.contentType(mediaType)
.body(resource);
}
```
#### PDF 文件下载
类似于预览功能,但需要修改HTTP响应头以触发浏览器下载行为而不是直接显示文档[^1]。
```java
@GetMapping("/download/{filename}")
public ResponseEntity<Resource> downloadPdf(@PathVariable String filename) throws IOException {
Path filePath = Paths.get("uploads/" + filename).toAbsolutePath().normalize();
Resource resource = new UrlResource(filePath.toUri());
if (!resource.exists() || !resource.isReadable()) {
throw new RuntimeException("Cannot find the requested file.");
}
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + resource.getFilename() + "\"");
return ResponseEntity.ok()
.headers(headers)
.contentLength(resource.contentLength())
.contentType(MediaType.APPLICATION_PDF)
.body(resource);
}
```
以上代码片段展示了如何构建用于上传、预览以及下载PDF文件的功能模块。这些操作均基于标准的RESTful API设计原则[^2]。
阅读全文
相关推荐


















