Second, SpringBoot realizes uploading files to the fastDFS file server

  The last article introduced how to use docker to install fastDFS file server, this article introduces the integration of springBoot to realize file upload to fastDFS file server

  1.pom.xml file add dependencies

<!-- 连接fastdfs文件系统 -->
<dependency>
        <groupId>net.oschina.zcx7878</groupId>
        <artifactId>fastdfs-client-java</artifactId>
        <version>1.27.0.0</version>
</dependency>       

  2. Create a configuration file fdfs_client.conf under the resource package  

  The value ip of tracker_server is the ip of your file server
connect_timeout=30
network_timeout=60
charset = UTF-8
http.tracker_http_port = 8888
http.anti_steal_token = no
http.secret_key =
tracker_server=ip:22122

  3. Create FastDFSConfig.java to load fdfs_client.conf configuration file

import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.TrackerClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

/**
 * fastDFS文件上传的配置
 */

@Configuration
public class FastDFSConfig {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Value ( "classpath: fdfs_client.conf" )
     private Resource ccs; 

    @Bean 
    public TrackerClient initClient () {
         try { 
            ClientGlobal.init (ccs.getFilename ()); 
            return  new TrackerClient (); 
        } catch (Exception e) { 
            log .info ( "FastDFS failed to create client" );
             return  null ; 
        } 
    } 
    
}

  4. Create a Cotroller for file upload, and the ip in the returned access path is the ip of your file server

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping("/file")
public class FileController {

    private Logger log = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private TrackerClient trackerClient;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception{
        if(file == null){
            throw new RuntimeException("文件不能为空");
        }
        //1.获取文件的完整名称
        String filename =file.getOriginalFilename ();
         if (StringUtils.isEmpty (filename)) {
             throw  new RuntimeException ("File does not exist" ); 
        } 
        // 2. Get the extended name of the file 
        String extName = filename.substring (filename.lastIndexOf (". ") + 1 ); 
        log.info ( " Full file name: "+ filename +" File extension: "+ extName); 
        NameValuePair [] metaList = new NameValuePair [1 ]; 
        metaList [ 0] = new NameValuePair (" fileName " , filename);
         // 3. Create trackerServer 
        TrackerServer trackerServer =trackerClient.getConnection ();
         // 4. Create a StorageServer reference, the value is null 
        StorageServer storageServer = null ;
         // 5. Create a StorageClient object, two parameters are required TrackerServer object, StorageServer reference 
        StorageClient storageClient = new StorageClient (trackerServer , storageServer);
         // 6. Use the StorageClient object to upload pictures. 
        String [] strings = storageClient.upload_file (file.getBytes (), extName, metaList);
         return "http: // ip: 8888 /" + strings [0] + "/" + strings [1 ]; 

    }

  5. At this time, use postman to call your file upload interface, and access it on the browser according to the returned path, you can successfully access the file you uploaded.

 

Guess you like

Origin www.cnblogs.com/chcha1/p/12732175.html