前端根据HttpServletResponse在线显示文件
时间: 2023-10-16 10:30:51 浏览: 24
可以使用以下代码实现:
```java
@RequestMapping("/file/download")
public void downloadFile(HttpServletResponse response) {
String filePath = "文件路径";
File file = new File(filePath);
if (file.exists()) {
try {
String fileName = URLEncoder.encode(file.getName(), "UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream");
response.setContentLength((int) file.length());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
OutputStream os = response.getOutputStream();
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
将上述代码添加到控制器中,访问 `/file/download` 即可在线显示文件。注意替换 `filePath` 为要在线显示的文件路径。响应头中的 `Content-Disposition` 属性指定了文件名,`Content-Type` 属性指定了文件类型。