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, I will briefly analyze the core code of the project in this article.
If it helps, welcome to like/see encouragement again, I will be happy for a long time ღ(´ ᴗ · ‘) than heart
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:
- The quality of the code is mediocre, with many optimizations like:
Controller
Layer code nested too much logic- No global exception handling (The code returns json data directly to the front end with error messages, which I don’t recommend)
- The return value does not need to pass
ObjectMapper
Convert to JSON format (ResponseEntity
+@RestController
Line) - .
- More companies are used, indicating that the overall function of the project is relatively stable and mature!
- 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/
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.
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.
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.
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("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.
/ * ** Processing 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) {
OfficePreviewType (image/ PDF/HTML); officePreviewType (image);
String officePreviewType = model.asMap().get("officePreviewType") = =null ? ConfigConstants.getOfficePreviewType() : model.asMap().get("officePreviewType").toString();
// 2. Obtain the URL
String baseUrl = BaseUrlFilter.getBaseUrl();// http://localhost:8012/ // 3 String suffix=fileAttribute.getSuffix();// The file suffix is like docx String fileName=fileAttribute.getName();// File name for example: Wuhan Cultural Market Management measures.docx // 4. Check whether the file is previewed in HTML format, i.e. check whether the file is excel boolean isHtml = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx"); // 5. Change the file suffix to.pdf or.html (in the case of excel files) String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf"); // 6. Output folder of converted files such as file-online-preview/jodconverter-web/ SRC /main/file/ Wuhan Cultural Market Management Method.pdf) String outFilePath = FILE_DIR + pdfName; // 7. Check whether the conversion has been performed before, if so, return directly, otherwise perform conversion // The file is cached the first time it is previewed if(! fileUtils.listConvertedFiles().containsKey(pdfName) || ! ConfigConstants.isCacheEnabled()) { String filePath; // Download the file 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) { // Perform operations on the converted file (change encoding mode) fileUtils.doActionConvertedFile(outFilePath); } if (ConfigConstants.isCacheEnabled()) { // add cache fileUtils.addConvertedFile(pdfName, fileUtils.getRelativePath(outFilePath)); } } } // 8. Select different preview modes based on officePreviewType For example, if officePreviewType is PDF, preview in PDF mode 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
Project address: github.com/kekingcn/kk…
I have compiled a high-quality original PDF resource to share with you for free. Most of the content is my original, and a few are from friends.
Download address: cowtransfer.com/s/fbed14f0c… .
My open source project recommendation
- JavaGuide: “Java Learning + Interview Guide” covers the core knowledge that most Java programmers need to master. Prepare for a Java interview, preferably JavaGuide!
- Guide xml-rpc – framework: Implemented by Netty+Kyro+Zookeeper A Custom RPC Framework Implemented by Netty+Kyro+Zookeeper
- Jsoncat: a lightweight HTTP framework that mimics but differs from Spring Boot
- Advancement: Good Habits for Programmers + Essentials for Interviews
- Springboot-guide: Not only SpringBoot but also important knowledge of Spring
- Awesome – Java: Collection of Awesome Java Project on Github
This article is formatted using MDNICE