JAVAEE - Icube Shop 04: Image Server FastDFS, Rich Text Editor KindEditor, Commodity Addition Completed

Posted by scerm on Thu, 09 May 2019 05:27:02 +0200

1. Learning Programs

1. Picture upload

a) Picture Server FastDFS

b) Picture upload function

2. Use KindEditor in Rich Text Editor

3. Completion of commodity addition function

 

2. Installation of Picture Server

1. The storage space can be expanded.

2. Provide a unified access method.

 

Using FastDFS, a distributed file system.Storage space can be expanded horizontally to make the server highly available.Each node is supported to have a backup machine.

 

2.1. What is FastDFS?

FastDFS is an open source distributed file system written in c language.FastDFS is tailored for the Internet, taking full account of redundant backup, load balancing, linear expansion and other mechanisms, and focusing on high availability, high performance and other indicators, it is easy to set up a high-performance file server cluster using FastDFS to provide file upload, download and other services.

 

2.2. FastDFS architecture

The FastDFS architecture includes Tracker server and Storage server.The client requests Tracker server for file upload and download, and the file upload and download are finally completed by Storage server through Tracker server scheduling.

Tracker servers are used for load balancing and scheduling, and Storage server s provide file upload services when uploading files through Tracker servers based on a number of strategies.You can call a tracker a tracking server or a dispatch server.

Storage server serves as a file store. The files uploaded by the client are ultimately stored on the Storage server. Storage server does not implement its own file system but manages the files using the operating system's file system.Storage can be referred to as a storage server.

 

 

 

The server side has two roles:

Tracker: Manage clusters, tracker also implements clusters.Each tracker node has equal status.

Collect the state of the Storage cluster.

Storage: Actually save the file

Storage is divided into groups, and the files saved between each group are different.There can be more than one member within each group, the content stored within the group members is the same, the status of group members is consistent, and there is no concept of master and subordinate.

 

2.3. File upload process

 

 

After the client uploads the file, the storage server returns the file ID to the client, which is used to access the index information of the file later.File index information includes: group name, virtual disk path, data level directory, file name.

 

 

 

n Group name: The name of the storage group in which the file is uploaded. The storage server returns after the file is uploaded successfully and needs to be saved by the client itself.

n Virtual disk path: The virtual path for the storage configuration, corresponding to the disk option store_path*.If store_path0 is configured it is M00, if store_path1 is configured it is M01, and so on.

n. Two-level directories for data: A two-level directory created by the storage server under each virtual disk path to store data files.

n File name: different from file upload.Generated by the storage server based on specific information, the file name contains information such as the source storage server IP address, file creation timestamp, file size, random number, file extension name, and so on.

 

2.4. File Download

 

 

 

2.5. Simplest FastDFS architecture

 

 

 

3. Picture Server Installation Method

3.1. Installation steps

Step 1: Unzip the picture server.

 

 

Step 2: Add a picture server to Vmware.

Step 3: Network configuration of Vmware.

 

 

Step 4: Turn on

 

 

Mobile: The network configuration does not change.To use a picture server, you need to keep your network configuration unchanged.

Copy: Re-generate a new network card mac address.

Ip address: 192.168.25.133

User name root, itcast

Password: itcast

4. Picture Server Use

4.1. Java client:

 

 

Maven environment:

 

 

4.2. Upload pictures

4.2.1. Upload steps

1. Load the configuration file, which contains the address of the tracker service.

Configuration file content: tracker_server=192.168.25.133:22122

2. Create a TrackerClient object.Directly new one.

3. Create a connection using the TrackerClient object to get a TrackerServer object.

4. Create a reference to StorageServer with a value of null

5. Creating a StorageClient object requires two parameters TrackerServer object and a reference to StorageServer

6. Use the StorageClient object to upload pictures.

7. Return an array.Path containing group name and image.

 

4.2.2. Code

public class FastDFSTest {

    @Test
    public void testFileUpload() throws Exception {
        // 1,Load the configuration file, which is tracker Address of the service.
        ClientGlobal.init("D:/workspaces-itcast/e3-manager-web/src/main/resources/resource/client.conf");
        // 2,Create a TrackerClient Object.direct new One.
        TrackerClient trackerClient = new TrackerClient();
        // 3,Use TrackerClient Object creates a connection to get a TrackerServer Object.
        TrackerServer trackerServer = trackerClient.getConnection();
        // 4,Create a StorageServer Reference, value is null
        StorageServer storageServer = null;
        // 5,Create a StorageClient Object, requires two parameters TrackerServer Object, StorageServer References
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        // 6,Use StorageClient Object to upload pictures.
        //Extension without "."
        String[] strings = storageClient.upload_file("D:/Documents/Pictures/images/200811281555127886.jpg", "jpg", null);
        // 7,Returns an array.Path containing group name and image.
        for (String string : strings) {
            System.out.println(string);
        }
    }
}

 


4.3. Upload using a tool class

 

You can leave it unspecified because the full path contains extensions, but you need to specify extensions if you are passing an array of bytes.

@Test
    public void testFastDfsClient() throws Exception {
        FastDFSClient fastDFSClient = new FastDFSClient("D:/workspaces-itcast/e3-manager-web/src/main/resources/resource/client.conf");
        String file = fastDFSClient.uploadFile("D:/Documents/Pictures/images/2f2eb938943d.jpg");
        System.out.println(file);
    }

 


5. Picture upload function

5.1. Functional analysis

 

 

 

Use KindEditor's multi-picture upload plug-in.

KindEditor 4.x Document

http://kindeditor.net/doc.php

 

Requested url:/pic/upload

Parameter: MultiPartFile uploadFile

Return value:

 

You can create a pojo corresponding return value.You can use map s

 

Business logic:

1. Receive the picture information uploadFile passed by the page

2. Upload pictures to the picture server.Implemented using encapsulated tool classes.The content and extension of the file are required.

3. The url of the picture returned by the picture server

4. Complete the URL of the picture and return a complete url.

5. Encapsulate the returned result into a Map object and return it.

 

 

1. The jar packages of commons-io and fileupload need to be added to the project.

2. Configure the multimedia parser.

<!-- Define file upload parser -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- Set default encoding -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- Set a maximum file upload value of 5 MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>
    </bean>

 


5.2. Controller 

@Controller
public class PictureController {
    
    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public Map fileUpload(MultipartFile uploadFile) {
        try {
            //1,Take file extension
            String originalFilename = uploadFile.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //2,Create a FastDFS Client
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:resource/client.conf");
            //3,Perform upload processing
            String path = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            //4,Stitching returned url and ip Address, assembled in complete url
            String url = IMAGE_SERVER_URL + path;
            //5,Return map
            Map result = new HashMap<>();
            result.put("error", 0);
            result.put("url", url);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            //5,Return map
            Map result = new HashMap<>();
            result.put("error", 1);
            result.put("message", "Picture upload failed");
            return result;
        }
    }
}

 


5.3. Resolve browser compatibility issues

KindEditor's picture upload plugin is not browser compatible.

Returns a java object using the @ResponseBody annotation,

Content-Type:application/json;charset=UTF-8

 

When returning a string:

Content-Type:text/plan;charset=UTF-8

 

 

 

Specify the content-type of the response result:

 

 

The content-type that KindEditor's multi-picture upload plug-in last responds to is a json string in text/plan format.Compatibility is best.

 

 

6. How to use rich text editor

6.1. Introduction to Rich Text Editor

 

 

KindEditor

http://kindeditor.net/

UEditor: Baidu Editor

http://ueditor.baidu.com/website/

CKEditor

http://ckeditor.com/

 

Pure js development, no relationship with background language.

 

6.2. Usage

Step 1: Introduce KindEditor's css and js code into jsp.

Step 2: Add a textarea control to the form.Is a vehicle for rich text editors.Similar to a data source.

Step 3: Initialize the rich text editor.Initialize using the officially provided method.

Step 4: Get rich text editor content.

Synchronize the rich text editor's content to the textarea control before submitting the form.

 

7. Realization of Commodity Add Function

7.1. Functional analysis

Requested url:/item/save

Parameter: Data of the form.You can use pojo to receive form data, requiring the pojo property to be consistent with the name property of the input.

Use the TbItem object to receive data from the form.

TbItem item,String desc

Return value:

Json data.It should contain a status attribute.

You can use E3Result to put it in e3-common.

 

Business logic:

1. Generate commodity id

Implementation scheme:

a) Uuid, string, not recommended.

b) Numeric type, not repeated.Date+Time+Random Number 20160402151333123123

c) Millisecond values + random numbers can be directly removed.Can be used.

d) Use redis.Incr.Recommended.

Generate commodity id using IDUtils

2. Complete the properties of the TbItem object

3. Insert data into the commodity table

4. Create a TbItemDesc object

5. Complete the properties of TbItemDesc

6. Insert data into the commodity description table

7,E3Result.ok()

 

7.2. Dao Layer

Insert data into the tb_item, tb_item_desc table

Reverse engineering can be used

 

7.3. Service Layer

Parameters: TbItem item,String desc

Business logic: Omit, participate above

Return value: E3Result

@Override
    public E3Result addItem(TbItem item, String desc) {
        // 1,Generate goods id
        long itemId = IDUtils.genItemId();
        // 2,completion TbItem Object Properties
        item.setId(itemId);
        //Commodity status, 1-Normal, 2-Underrack, 3-delete
        item.setStatus((byte) 1);
        Date date = new Date();
        item.setCreated(date);
        item.setUpdated(date);
        // 3,Insert data into commodity table
        itemMapper.insert(item);
        // 4,Create a TbItemDesc object
        TbItemDesc itemDesc = new TbItemDesc();
        // 5,completion TbItemDesc Properties of
        itemDesc.setItemId(itemId);
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(date);
        itemDesc.setUpdated(date);
        // 6,Insert data into the commodity description table
        itemDescMapper.insert(itemDesc);
        // 7,E3Result.ok()
        return E3Result.ok();
    }

 


Publishing Services

 

7.4. Appearance

Reference Services

 

7.4.1. Controller

Requested url:/item/save

Parameters: TbItem item,String desc

Return value: E3Result

@RequestMapping(value = "/save",method = RequestMethod.POST)
    @ResponseBody
    public E3Result saveItem(TbItem item, String desc) {
        E3Result result = itemService.addItem(item, desc);
        return result;
    }

 


7.5. Jobs

Commodity modification, deletion, shelf and shelf.

Topics: Java KindEditor network JSON Vmware