项目中有个需求,html body里面的内容,想转换成word文档,本来没想到好的办法,只能先创建一个临时文件,后续操作都以这个临时文件做媒介,用完之后删除掉,最后想到这个不是很好的办法,那就在网上一直找解决方法,最后还是找到了。
由于 body里面包含了大量的引号,和需求人员商定,前端传过来的就是 base64编码,后端取到之后进行解码操作,本例是返回了阿里云oss链接,其实获取到输出流之后完全可以放到httpSertvletResponse中就可以了,下面是具体的代码:
/**
* 通过html源码生成oss文件并返回链接
* @param htmlSourceCode
* @return
*/
private static String createOssFile(String htmlSourceCode) {
String signedObjectURL = null;
ByteArrayInputStream byteArrayInputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
ByteArrayInputStream byteArrayInputStreamTarget = null;
POIFSFileSystem poifs = null;
DirectoryEntry directory = null;
try {
//输入流
byte htmlSourceCodeBytes[] = htmlSourceCode.getBytes();
byteArrayInputStream = new ByteArrayInputStream(htmlSourceCodeBytes);
//临时的输出流,利用poi往输出流里面写数据
byteArrayOutputStream = new ByteArrayOutputStream();
//写信息到输出流
poifs = new POIFSFileSystem();
directory = poifs.getRoot();
directory.createDocument("WordDocument", byteArrayInputStream);
poifs.writeFilesystem(byteArrayOutputStream);
//转换OutPutStream 到 InputStream
byteArrayInputStreamTarget = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
//上传文件到oss服务器
String dirFileame = fileUploadToOssByInputStream("htmlToWord",byteArrayInputStreamTarget);
signedObjectURL = ossUtils.getForEverUrl(dirFileame);
} catch (IOException e) {
log.error("转换文件出现异常",e);
}finally {
try {
byteArrayInputStream.close();
byteArrayOutputStream.close();
byteArrayInputStreamTarget.close();
poifs.close();
} catch (IOException e) {
log.error("关闭流出现异常",e);
}
}
return signedObjectURL;
}