将文件转化为数据流,对文件进行下载
public static void writeFileToStream(FileInputStream fileInputStream, OutputStream outputStream, Long size) throws IOException {
FileChannel fileChannel = null;
WritableByteChannel writableByteChannel = null;
try {
fileChannel = fileInputStream.getChannel();
writableByteChannel = Channels.newChannel(outputStream);
fileChannel.transferTo(0, size, writableByteChannel);
outputStream.flush();
} catch (Exception e) {
} finally {
fileInputStream.close();
outputStream.close();
fileChannel.close();
writableByteChannel.close();
}
}
@GetMapping(value = "/previewTest/{filename}")
public void preview(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {
String filePath = path +filename;
File file = new File(filePath);
FileProcess.writeFileToStream(new FileInputStream(filePath), response.getOutputStream(), file.length());
}