SpringMVC如何把后台文件打印到前台
#代码知识 发布时间: 2026-01-12
实现效果如下:
代码为:
@RequestMapping(value = "/tools/printContract")
public void cell(HttpServletResponse response,HttpServletRequest request,String outName) {
//根据outName获取到保存在服务器上的文件
String filePath = request.getSession().getServletContext().getRealPath(ImgUtil.TOOLS_PATH+ImgUtil.TOOLS_TXT)+'/'+outName+".txt";
try(OutputStream out = response.getOutputStream()) {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
String dateString = formatter.format(currentTime);
//fileName是输出的文件的名字(不支持中文),包括了后缀
String fileName = "EncryptFile_" + dateString + ".txt";
byte[] bytes = FileEcodeUtil.file2byte(filePath);
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition","attachment;filename=" + fileName);
response.setContentLength(bytes.length);
out.write(bytes);
out.flush();
} catch (IOException e) {
//e.printStackTrace();
}
}
//上面用到的file2byte方法为:
public static byte[] file2byte(String filePath) {
byte[] buffer = null;
File file = new File(filePath);
try (FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
} catch (Exception e) {
// e.printStackTrace();
}
return buffer;
}
需要注意:返回值的类型是void 而不是String,不能返回到某一个页面,否则服务器会抛出IllegalStateException异常,虽然在页面上表现不出来。
java.lang.IllegalStateException: Cannot create a session after the response has been committed
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
代码知识SEO上一篇 : C语言实现抢红包算法
下一篇 : 使用Java 实现一个“你画手机猜”的小游戏
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!