java 文件流上传pdf文件接口实现
时间: 2023-08-29 16:09:13 浏览: 198
您好!以下是一个用于上传PDF文件的Java文件流上传接口的实现示例:
```java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "Please select a file to upload.";
}
try {
// 获取文件输入流
InputStream inputStream = file.getInputStream();
// 指定上传的目录路径
String uploadDir = "/path/to/upload/dir/";
// 检查文件类型
String originalFilename = file.getOriginalFilename();
if (!originalFilename.toLowerCase().endsWith(".pdf")) {
return "Only PDF files are allowed.";
}
// 创建目标文件的完整路径
String filePath = uploadDir + originalFilename;
// 创建目标文件
File targetFile = new File(filePath);
// 创建文件输出流
FileOutputStream outputStream = new FileOutputStream(targetFile);
// 将输入流中的数据写入到输出流中
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭流
inputStream.close();
outputStream.close();
return "File uploaded successfully!";
} catch (IOException e) {
e.printStackTrace();
return "Failed to upload file.";
}
}
}
```
与之前的示例相比,此代码段添加了一个检查文件类型的步骤,确保只允许上传PDF文件。在该示例中,我们假设只接受以`.pdf`为后缀的文件。
请注意,您需要根据实际情况修改上传目录的路径以及处理异常的方式。
希望以上代码能满足您的需求!如果您有任何疑问,请随时提问。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)