环境:jdk1.8,springboot2.5.3,项目端口号:9100
1.待转换的文件
一、路径
二、文件内容
2.controller中代码
java
package com.example.pdf.controller;
import com.example.pdf.service.GetFileStreamService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
/**
* @author
* @date 2024/3/29 16:28
* @describe
*/
@RestController
@RequestMapping(value = "test")
public class GetFileStreamController {
@Resource
private GetFileStreamService getFileStreamService;
/**
* 获取文件流
*/
@GetMapping("getFileStream")
public void getFileStream(HttpServletResponse response) {
getFileStreamService.getFileStream(response);
}
}
3.service中代码
java
package com.example.pdf.service;
import javax.servlet.http.HttpServletResponse;
/**
* @author
* @date 2024/3/29 16:30
* @describe
*/
public interface GetFileStreamService {
/**
* 获取文件流
* @param response
*/
void getFileStream(HttpServletResponse response);
}
4.实现类代码
java
package com.example.pdf.service.impl;
import com.example.pdf.service.GetFileStreamService;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
/**
* @author
* @date 2024/3/29 16:31
* @describe
*/
@Service
public class GetFileStreamServiceImpl implements GetFileStreamService {
/**
* 获取文件流
*/
@Override
public void getFileStream(HttpServletResponse response) {
// 指定文件路径,获取file文件
File file = new File("E:\\Desktop\\temps\\test.pdf");
try {
// 将文件转为文件输入流
FileInputStream fileInputStream = new FileInputStream(file);
// 获取响应的输出流
OutputStream outputStream = response.getOutputStream();
// 将文件转成字节数组,再将数组写入响应的输出流
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 刷新输出流
outputStream.flush();
// 关闭流
fileInputStream.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}