Using fastDFS client to transform file upload

Keywords: Java Spring xml github

java client

Mr. Yu Qing provides a java client, but as a C programmer, the Java code written can be imagined. And it's been a long time since maintenance.

Here we recommend an open source FastDFS client that supports the latest spring boot 2.0.

It is very simple to configure and use. It supports connection pool, automatic generation of thumbnails, crazy pulling, cool hanging and exploding.

Address: tobato/FastDFS_client

Next, we will transform the learn upload project with FastDFS.

Introducing dependency

In the parent project, we have managed the dependency. The version is:

<fastDFS.client.version>1.26.2</fastDFS.client.version>

Therefore, here we can directly introduce coordinates into pom.xml of Taotao upload project:

<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
</dependency>

Introduce configuration class

Pure java configuration:

@Configuration
@Import(FdfsClientConfig.class)
// Solve the problem of jmx repeatedly registering bean s
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FastClientImporter {
    
}

Write FastDFS properties

Add the following to the application.yml configuration file:

fdfs:
  so-timeout: 1501 # Timeout time
  connect-timeout: 601 # Connection timeout
  thumb-image: # thumbnail
    width: 60
    height: 60
  tracker-list: # tracker address: your virtual machine server address + port (default is 22122)
    - 192.168.56.101:22122

Configure hosts

In the future, access the image resources on the fastDFS server through the domain name: image.learn.com. Therefore, you need to proxy to the virtual machine address:

Configure the hosts file so that image.learn.com can access the fastDFS server

test

To create a test class:

copy in the following:

@SpringBootTest
@RunWith(SpringRunner.class)
public class FastDFSTest {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;

    @Test
    public void testUpload() throws FileNotFoundException {
        // Files to upload
        File file = new File("C:\\Users\\leon\\Pictures\\xbx1.jpg");
        // Upload and save the image, parameters: 1-uploaded file stream 2-file size 3-file suffix 4-no matter what
        StorePath storePath = this.storageClient.uploadFile(
                new FileInputStream(file), file.length(), "jpg", null);
        // Paths with groups
        System.out.println(storePath.getFullPath());
        // Paths without grouping
        System.out.println(storePath.getPath());
    }

    @Test
    public void testUploadAndCreateThumb() throws FileNotFoundException {
        File file = new File("C:\\Users\\leon\\Pictures\\xbx1.jpg");
        // Upload and generate thumbnails
        StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage(
                new FileInputStream(file), file.length(), "png", null);
        // Paths with groups
        System.out.println(storePath.getFullPath());
        // Path without grouping
        System.out.println(storePath.getPath());
        // Get thumbnail path
        String path = thumbImageConfig.getThumbImagePath(storePath.getPath());
        System.out.println(path);
    }
}

Result:

group1/M00/00/00/wKg4ZVsWl5eAdLNZAABAhya2V0c424.jpg
M00/00/00/wKg4ZVsWl5eAdLNZAABAhya2V0c424.jpg
group1/M00/00/00/wKg4ZVsWmD-ARnWiAABAhya2V0c772.png
M00/00/00/wKg4ZVsWmD-ARnWiAABAhya2V0c772.png
M00/00/00/wKg4ZVsWmD-ARnWiAABAhya2V0c772_60x60.png

Access the first path of the second group:

Access the last path (thumbnail path), and pay attention to add group name (group1):

Transform upload logic

@Service
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/jpeg", "image/gif");

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    public String upload(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();
        // Type of verification file
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            // Illegal file type, return null directly
            LOGGER.info("Illegal file type:{}", originalFilename);
            return null;
        }

        try {
            // Content of verification file
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                LOGGER.info("Illegal content:{}", originalFilename);
                return null;
            }

            // Save to server
            // file.transferTo(new File("C:\\learn\\images\\" + originalFilename));
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            // Generate url address, return
            return "http://image.learn.com/" + storePath.getFullPath();
        } catch (IOException e) {
            LOGGER.info("Server internal error:{}", originalFilename);
            e.printStackTrace();
        }
        return null;
    }
}

Just remove the logic of the original saved file and upload it to FastDFS.

test

Pass the RestClient test:

Page Test upload

Found upload successful:

 

2046 original articles published, 46 praised, 120000 visitors+
His message board follow

Posted by changeback on Tue, 04 Feb 2020 04:55:40 -0800