在Controller的方法中调用下面的方法,实现文件下载。
有两种需求:
- 要下载的文件与服务在同一个服务器上,可通过文件路径创建File对象,下载文件;
- 要下载的文件与服务在不同一个服务器上,可在服务程序中从文件服务器下载文件,转为byte数组,再调用该方法;
/**
* 在Controller的方法中调用此方法,实现文件下载
* @param resp
* @param fileBytes 文件的byte数组
* @param fileName
* @throws IOException
*/
private void downloadFile(HttpServletResponse resp, byte[] fileBytes, String fileName) throws IOException {
resp.setHeader("content-type", "application/octet-stream");
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
byte[] buff = new byte[1024];
BufferedInputStream bufferedInputStream = null;
OutputStream outputStream = null;
try {
outputStream = resp.getOutputStream();
// ————————————————————————————
// 文件File对象转BufferedInputStream: 给方法传入文件路径和文件名
// File file = new File(filePath, fileName);
// FileInputStream fis = new FileInputStream(file);
// bufferedInputStream = new BufferedInputStream(fis);
// ————————————————————————————
bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(fileBytes), fileBytes.length);
int num = bufferedInputStream.read(buff);
while (num != -1) {
outputStream.write(buff, 0, num);
outputStream.flush();
num = bufferedInputStream.read(buff);
}
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
} finally {
if (bufferedInputStream != null) {
bufferedInputStream.close();
}
}
}