文件的下载使用流的形式传输
maven依赖
<minio.version>7.1.4</minio.version>
控制层接口
/**
* @fileName 文件名称(无后缀格式)
*/
@ApiOperation(value = "下载报告")
@GetMapping("/download")
public void downloadFile(@RequestParam String fileName, HttpServletResponse response) {
MinioUtil.downloadFile(fileName + ".docx", response);
}
调用minio工具类的方法
public static void downloadFile(String fileName, HttpServletResponse response) {
// 创建输入流
InputStream is = null;
try {
// 获取对象的元数据
ObjectStat stat = minioClient.statObject(StatObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).build());
// 响应 设置内容类型
response.setContentType(stat.contentType());
// 响应 设置编码格式
response.setCharacterEncoding("UTF-8");
// 响应 设置头文件
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
// 输入流
is = minioClient.getObject(GetObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).build());
// 将字节从输入流复制到输出流
IOUtils.copy(is, response.getOutputStream());
} catch (Exception e) {
throw new RuntimeException("下载文件异常", e);
} finally {
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
下载的文件的内容以html格式展示
@SneakyThrows
@ApiOperation(value = "报告查询-高亮搜索关键字")
@GetMapping("/selectReport/{fileName}")
public String selectSearch(@PathVariable String fileName, HttpServletResponse response) {
return reportService.selectSearch(fileName, response);
}
@Override
public String selectSearch(String fileName, HttpServletResponse response) throws IOException {
// 流转成文件,wordToHtml
InputStream inputStream = MinioUtil.downloadFileStream(fileName + ".html");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = inputStream.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
} catch (Exception e) {
throw new BusinessException("Illegal flow.");
} finally {
try {
inputStream.close();
} catch (IOException e) {
log.error("file stream shutdown failed.");
}
}
return baos.toString("GB2312");
}
/**
* 获取文件流(*********注意使用完请关闭流*********)
*
* @param fileName
*/
public static InputStream downloadFileStream(String fileName) {
try {
return minioClient.getObject(GetObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).build());
} catch (Exception e) {
throw new RuntimeException("下载文件异常", e);
}
}
public InputStream getObject(GetObjectArgs args)
throws ErrorResponseException, IllegalArgumentException, InsufficientDataException,
InternalException, InvalidBucketNameException, InvalidKeyException,
InvalidResponseException, IOException, NoSuchAlgorithmException, ServerException,
XmlParserException {
checkArgs(args);
args.validateSsec(this.baseUrl);
Long offset = args.offset();
Long length = args.length();
if (length != null && offset == null) {
offset = 0L;
}
Multimap<String, String> headers = HashMultimap.create();
if (length != null) {
headers.put("Range", "bytes=" + offset + "-" + (offset + length - 1));
} else if (offset != null) {
headers.put("Range", "bytes=" + offset + "-");
}
if (args.ssec() != null) {
headers.putAll(Multimaps.forMap(args.ssec().headers()));
}
Multimap<String, String> queryParams = HashMultimap.create();
if (args.versionId() != null) queryParams.put("versionId", args.versionId());
Response response = executeGet(args, headers, queryParams);
return response.body().byteStream();
}
文件的上传
public ResultResp importReportTemplateResult(MultipartFile file) {
Assert.notNull(file, "上传文件不能为空...");
ResultResp resultResp = new ResultResp();
try {
HashMap<String, Object> resMaps = new HashMap<>();
// word内容 转Html 然后拆分文本和内容.
String htmlContent;
//上传minio 然后返回到前端
String fileName = file.getOriginalFilename();
String newFileName = MinioUtil.uploadFile(file);
// ("filePath", filePath);
//获取文件的后缀
String extension = StringUtils.getFilenameExtension(fileName);
//根据文件类型进行对应的解析
if (StringUtils.hasText(extension) && extension.toLowerCase().equals(WordTypeEnums.DOCX.getCode())) {
htmlContent = WordToHtml.word2007ToHtml(file, newFileName);
resMaps.put("html", htmlContent);
} else if (StringUtils.hasText(extension) && extension.toLowerCase().equals(WordTypeEnums.DOC.getCode())) {
// word03转html
htmlContent = WordToHtml.word2003ToHtml(file);
resMaps.put("html", htmlContent);
} else {
resMaps.put("html", "");
resMaps.put("msg", "未匹配到该类型的文件...");
}
resultResp.setResp(resMaps);
} catch (IOException | ParserConfigurationException | TransformerException e) {
e.printStackTrace();
resultResp.setResp("导入文件异常:" + e.getMessage());
}
return resultResp;
}
word转html
依赖poi-ooxml包
1.Word2003文档仅使用“.doc”格式保存。
2.Word2007文档的默认保存格式为“.docx”,并且也支持“.doc”格式的读取与保存。
/**
* 将Word2007+转成Html,并且上传到minio服务器
* 支持docx格式
*
* @param multipartFile 文件源
* @throws Exception
*/
public static String word2007ToHtml(MultipartFile multipartFile, String fileName) throws IOException {
// 创建输入流null
InputStream input = null;
// 创建字节输出流null
ByteArrayOutputStream outputStream = null;
// 创建字节输入流null
ByteArrayInputStream inputStream = null;
try {
// 获取上传文件的输入流
input = multipartFile.getInputStream();
XWPFDocument document = new XWPFDocument(input);
// 文件获取所有图片返回一个集合list
List<XWPFPictureData> list = document.getAllPictures();
outputStream = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(document, outputStream, null);
// 分割文件名称
String newFileName = fileName.substring(0, fileName.indexOf(".")) + ".html";
String doc = setImg(outputStream.toString(), list);
doc = doc.replaceAll("\"", "'").replaceAll("\\n", "").replaceAll("\\r", "");
// 输入流字节格式设置
inputStream = new ByteArrayInputStream(doc.getBytes("GB2312"));
// 返回minio上传文件(以字节的形式)方法-->返回文件名称
return MinioUtil.uploadByteFile(inputStream, newFileName);
} catch (IOException e) {
throw new BusinessException("文件转化异常");
} finally {
// 流关闭
if (input != null) {
input.close();
}
if (outputStream != null) {
outputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
/**
* word2003转换成html
* 对于doc,可以用下面这种方式:
*
* @throws Exception
*/
public static String word2003ToHtml(MultipartFile multipartFile) throws IOException, ParserConfigurationException, TransformerException {
InputStream input = multipartFile.getInputStream();
HWPFDocument wordDocument = new HWPFDocument(input);
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//设置图片存储位置
wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> {
//上传minio
String minioPath = MinioUtil.uploadByteFile(content, suggestedName);
return minioPath;
});
//解析word文档
wordToHtmlConverter.processDocument(wordDocument);
org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(htmlDocument), new StreamResult(buffer));
String str = buffer.toString();
str = str.replaceAll("\"", "'").replaceAll("\\n", "").replaceAll("\\r", "");
return str;
}
html转word
public class HtmlToWord {
/**
* html转Word,并且上传minio
*
* @param content
* @return
* @throws IOException
*/
public static void htmlToWord2007(String content, String fileName) throws IOException {
InputStream is = null;
ByteArrayOutputStream os = null;
POIFSFileSystem fs = null;
ByteArrayInputStream bais = null;
try {
is = new ByteArrayInputStream(content.getBytes("GB2312"));
os = new ByteArrayOutputStream();
fs = new POIFSFileSystem();
fs.createDocument(is, "WordDocument");
fs.writeFilesystem(os);
bais = new ByteArrayInputStream(os.toByteArray());
MinioUtil.uploadByteFile(bais, fileName + ".docx");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (fs != null) {
fs.close();
}
if (bais != null) {
bais.close();
}
}
}
}