preface

It took a while to set up the environment last night, and I wasted most of my time installing openOffice as a dependent environment (Mac requires manual installation). Then, step by step functional demonstrations, documentation, debugging of the project, and a brief study of the core code before writing this article. In addition, this article I will simply analyze the core code of the project, xiaobian here also prepared a Spring Boot mind map, need friends can click to view, pay attention to the public number: Kirin bug.

Project introduction

KkFileView:

KkFileView is a project solution using Spring Boot to create files and documents online preview. Support doc, DOCx, PPT, PPTX, XLS, XLSX, ZIP, RAR, MP4, MP3 and many types of text such as TXT, HTML, XML, Java, properties, SQL, JS, MD, JSON, conf, INI, vue, PHP, py, bat, gitignore and other files online preview

KkFileView is simply an online preview solution for common file types.

Overall I think kkFileView is a great open source project and the need for online file preview is very common. Thanks open source!

Next, I will evaluate kkFileView from the perspective of a “God” from multiple dimensions:

  1. The quality of the code is mediocre, with many optimizations like:
    • The Controller layer code has too much nested logic

    • No global exception handling (

      The code returns json data directly to the front end with error messages, which I don’t recommend

      )

    • Return value does not need to be converted to JSON format via ObjectMapper.

    • .

  2. More companies are used, indicating that the overall function of the project is relatively stable and mature!
  3. The overall logic of the code is still more clear, easier to understand, give the authors a thumbs up!

Environment set up

Cloning project

To clone the project locally, run the following command:

git clone https://gitee.com/kekingcn/file-online-preview.git
Copy the code

Installing OpenOffice

Previews of Office-type files rely on OpenOffice, so we need to install OpenOffice first (it’s built-in for Windows, automatically installed for Linux, and manually installed for Mac OS).

Here’s how to install OpenOffice on a Mac.

You can install the latest version of OpenOffice by using the following command:

brew cask install openoffice
Copy the code

However, this method may be slow to download, you can download the DMG installation package directly from the official website.

The official download address: www.openoffice.org/download/

Download OpenOffice

Many of you are asking: What is OpenOffice?

OpenOffice is a free and open source word processing software developed by Apache. It supports mainstream operating systems such as Windows, Liunx, and OS X.

OpenOffice is similar to Office for Windows, but is open source and free.

why openoffice

Start the project

Run the main method of FilePreviewApplication. After the service is started, visit http://localhost:8012/ and you will see the following interface, indicating that the service is started successfully.

Project started successfully

use

We first uploaded 3 different types of files to demonstrate the preview of images, PDF and Word documents respectively.

Image preview

KkFileView supports preview of JPG, JPEG, PNG, GIF and other formats, including flipping, zooming and other operations.

A preview of the image is shown below.

A preview of the image

Preview of Word documents

KkFileView supports doc, DOCX document preview.

In addition, Word Preview provides two modes according to Word size and network speed:

  • Each page of Word is converted to picture preview
  • Convert the entire Word document to a PDF and then preview the PDF.

The application scenarios of the two modes are as follows

  • Image preview: Word file is large (loading PDF is slow).
  • PDF preview: Intranet access (fast PDF loading).

Image preview mode:

PDF Preview mode The preview looks like this:

Preview of PDF documents

KkFileView supports PDF document preview. Similar to Word document preview, PDF preview offers two modes:

  • Each page of Word is converted to picture preview
  • Convert the entire Word document to a PDF and then preview the PDF.

Since it looks like a preview of the Word document, I won’t include images here.

File preview core code analysis

The API layer

The interface that file preview calls is /onlinePreview.

By analyzing /onlinePreview interface, we found that after receiving the preview request, the backend will filter out the information it needs from the URL and request, such as file suffixes and file names.

The filePreviewHandle() method of the FilePreview class is then called. The filePreviewHandle() method is the core method for implementing file previews.

@RequestMapping(value = "/onlinePreview") public String onlinePreview(String url, Model model, HttpServletRequest req) { FileAttribute fileAttribute = fileUtils.getFileAttribute(url); req.setAttribute("fileKey", req.getParameter("fileKey")); model.addAttribute("pdfDownloadDisable", ConfigConstants.getPdfDownloadDisable()); model.addAttribute("officePreviewType", req.getParameter("officePreviewType")); FilePreview filePreview = previewFactory.get(fileAttribute); Logger. info(" Preview file URL: {}, previewType: {}", url, fileAttribute.getType()); return filePreview.filePreviewHandle(url, model, fileAttribute); }Copy the code

FilePreview is the FilePreview interface. Different file types of preview implement FilePreview interface and implement the filePreviewHandle() method.

File preview interface

public interface FilePreview {
    String filePreviewHandle(String url, Model model, FileAttribute fileAttribute);
}
Copy the code

Previews for different file types implement the FilePreview interface, as shown in the figure below.

Previews of different file types implement the FilePreview interface and then override the filePreviewHandle() method. For example: OfficeFilePreviewImpl is mainly responsible for processing office file preview, PdfFilePreviewImpl is mainly responsible for processing PDF file preview.

File preview specific implementation analysis

Here we take the office file preview as the entrance to analyze.

First of all, it should be clear that the preview of Excel files is achieved by converting Excel files to HTML. The preview of other office files is achieved by converting files to PDF or images.

Let me give you an example. We uploaded a Word file named Wuhan Cultural Market Management Method.docx and previewed it. Two related files will be generated in the path of jodconverter-web/ SRC /main/file. These two files correspond to the PDF preview and image preview we mentioned respectively.

  • Wuhan Cultural Market Management Measures. PDF
  • A series of images converted from a Word file

We take a file named Wuhan Cultural Market Management Method.docx as an example to illustrate how this is done in the code.

By analyzing the code, we located the OfficeFilePreviewImpl class that handles previews of Office files.

@service public class OfficeFilePreviewImpl implements FilePreview {}Copy the code

Let’s take a quick look at the core method that implements preview in the OfficeFilePreviewImpl class is filePreviewHandle.

Note: the logic of this part of the code is not clear enough, but also can extract method optimization to make people easier to understand, interested partners can start their own reconstruction, and then to give the author a PR.

@Override public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) { // 1. OfficePreviewType = officePreviewType = image/ PDF/HTML No system default (image) String officePreviewType = model.asmap ().get("officePreviewType") == null? ConfigConstants.getOfficePreviewType() : model.asMap().get("officePreviewType").toString(); BaseUrl = baseurlfilter.getBaseurl (); baseUrl = baseurlfilter.getBaseurl (); // http://localhost:8012/ // 3. String suffix= fileattribute.getsuffix (); // File extension like docx String fileName= fileattribute.getName (); // File name such as: Measures for the management of cultural market in wuhan city. Docx / / 4. Determine whether as HTML preview is also judge whether file for excel Boolean isHtml = suffix. EqualsIgnoreCase (" XLS ") | | suffix.equalsIgnoreCase("xlsx"); // 5. Change the fileName extension to.pdf or.html (for excel files) String pdfName = filename.substring (0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf"); // 6. The output folder of the converted file is file-online-preview/jodconverter-web/ SRC /main/file/ Wuhan Cultural Market Management Method. PDF) String outFilePath = FILE_DIR + pdfName; If (!) {if (!) {if (!) {if (!) {if (! fileUtils.listConvertedFiles().containsKey(pdfName) || ! ConfigConstants.isCacheEnabled()) { String filePath; ReturnResponse<String> Response = downloadUtils. DownLoad (fileAttribute, null); if (0 ! = response.getCode()) { model.addAttribute("fileType", suffix); model.addAttribute("msg", response.getMsg()); return "fileNotSupported"; } filePath = response.getContent(); if (StringUtils.hasText(outFilePath)) { officeToPdf.openOfficeToPDF(filePath, outFilePath); If (isHtml) {/ / on the converted file operations (change the encoding) fileUtils. DoActionConvertedFile (outFilePath); } the if (ConfigConstants isCacheEnabled ()) {/ / to join the cache fileUtils. AddConvertedFile (pdfName, fileUtils.getRelativePath(outFilePath)); OfficePreviewType = officePreviewType = PDF if (! isHtml && baseUrl ! = null && (OFFICE_PREVIEW_TYPE_IMAGE.equals(officePreviewType) || OFFICE_PREVIEW_TYPE_ALL_IMAGES.equals(officePreviewType))) { return getPreviewType(model, fileAttribute, officePreviewType, baseUrl, pdfName, outFilePath, pdfUtils, OFFICE_PREVIEW_TYPE_IMAGE); } model.addAttribute("pdfUrl", pdfName); return isHtml ? "html" : "pdf"; }Copy the code

conclusion

The above is a small editor to share a Spring Boot build an online file preview system, described the function of the demonstration, record, debugging project. Spring Cloud, Mybatis, JVM, Zookeeper, Spring