public String download(MultipartFile file, String url) throws Exception {
String fileName = file.getOriginalFilename();
//获取文件类型
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
String doc = "doc";
String docx = "docx";
String html = "html";
Calendar instance = Calendar.getInstance();
int year = instance.get(Calendar.YEAR);
int month = instance.get(Calendar.MONTH) + 1;
int day = instance.get(Calendar.DAY_OF_MONTH);
String wordName = IdUtil.fastSimpleUUID();
// 要转换的临时文件
String targetFileName ="E:/" year + "/" + month + "/" + day + "/" + wordName + "/";
String saveUrl = targetFileName + wordName + "." + html;
//文件类型如果不是doc或者docx返回错误
if (doc.equals(fileType) || docx.equals(fileType)) {
try {
//去水印
if (!PdfUtils1.getLicense()) {
throw new Exception("com.aspose.words lic ERROR!");
}
//读取word
try (InputStream fileInputStream = file.getInputStream()) {
Document document = new Document(fileInputStream);
//生成临时html
document.save(saveUrl, new HtmlSaveOptions(SaveFormat.HTML));
//读取文件内容
// targetFileName:文件夹地址
//saveUrl:文件的保存路径
// url:url是从前端获取的服务器端口加读取文件返回留的接口
// window.location.origin +
// "/zhbgapi?fileurl=",
String fileContent = htmlPath(targetFileName, saveUrl, url);
return fileContent;
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
这个方法是将word转成html然后读取html文本 然后遍历文件中所有文件
如果有图片存在将src=“图片路径'换成ser=“你的文件文件流接口+文件地址”代码如下
public String htmlPath(String targetFileName, String htmlPath, String url) {
File htmlFile = new File(htmlPath);
// 读取 HTML 文件内容
try (FileReader fileReader = new FileReader(htmlFile);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
StringBuilder stringBuilder = new StringBuilder();
String line = bufferedReader.readLine();
while (line != null) {
stringBuilder.append(line);
line = bufferedReader.readLine();
}
String htmlContent = stringBuilder.toString();
//遍历html所在的文件夹获取所有图片名称
File file = new File(targetFileName);
File[] files = file.listFiles();
if (files.length > 0) {
for (File file1 : files) {
String fileExtension = "";
String fileName = file1.getName();
int dotIndex = fileName.lastIndexOf(".");
//获取文件后缀
if (dotIndex != -1 && dotIndex < fileName.length() - 1) {
fileExtension = fileName.substring(dotIndex + 1);
}
//如果后缀是图片的话将原html中的文件路径置换成可以访问的路径
boolean existed = "png".equals(fileExtension) || ("jpg".equals(fileExtension) || ("jpeg".equals(fileExtension)));
if (existed) {
htmlContent = htmlContent.replace(fileName, url + targetFileName + fileName);
}
}
}
bufferedReader.close();
fileReader.close();
return htmlContent;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
将返回的字符串直接放到富文本上就可以回显啦,打完收工!!!!