SpringMVC如何把后台文件打印到前台

网友投稿 364 2023-04-02

SpringMVC如何把后台文件打印到前台

SpringMVC如何把后台文件打印到前台

实现效果如下:

代码为:

@RequestMapping(value = "/tools/printContract")

public void cell(HttpServletResponse response,HttpServletRequest request,String outName) {

//根据outName获取到保存在服务器上的文件

String filePath = request.getSession().getServletContext().getRealhttp://Path(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";

OdOlDIMxdbyte[] 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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot中的springSession的存储和获取实现
下一篇:mac下idea的svn密码记不住的问题及处理方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~