springboot整合fastdfs

首先pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cxy</groupId>
    <artifactId>fastdfs</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fastdfs</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.tobato</groupId>
            <artifactId>fastdfs-client</artifactId>
            <version>1.26.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

yml

# 分布式文件系统FDFS配置
fdfs:
  soTimeout: 1500 #socket连接超时时长
  connectTimeout: 600 #连接tracker服务器超时时长
  resHost: 192.168.25.133
  storagePort: 80
  thumbImage: #缩略图生成参数,可选
      width: 150
      height: 150
  trackerList: #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port
    - 192.168.25.133:22122
spring:
  http:
    multipart:
      max-file-size: 100MB # 最大支持文件大小
      max-request-size: 100MB # 最大支持请求大小

启动类:

package com.cxy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FastdfsApplication {

    public static void main(String[] args) {
        SpringApplication.run(FastdfsApplication.class, args);
    }

}

结果类:

package com.cxy.bean;

public class Result<T> {
    public Result(){} ;
     
    public static <T> Result<T> createResult(){
        return new Result<T>() ;
    }
 
 
    private T content;
    private int code;
    private String message ;
 
    public T getContent() {
        return content;
    }
 
    public Result<T> setContent(T content) {
        this.content = content;
        return this ;
    }
 
    public int getCode() {
        return code;
    }
 
    public Result<T> setCode(int code) {
        this.code = code;
        return this ;
    }
 
    public String getMessage() {
        return message;
    }
 
    public Result<T> setMessage(String message) {
        this.message = message;
        return this ;
    }


}

上传类:

package com.cxy.bean;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

@Component
public class FastDFSClientWrapper {
    
     
    @Autowired
    private FastFileStorageClient storageClient;
 
    /**
     * 上传文件
     * 
     * @param file
     *            文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }
 
    /**
     * 将一段字符串生成一个文件上传
     * 
     * @param content
     *            文件内容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream, buff.length, fileExtension, null);
        return getResAccessUrl(storePath);
    }
 
    // 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        String fileUrl = storePath.getFullPath();
        return fileUrl;
    }
 
    /**
     * 传图片并同时生成一个缩略图 "JPG", "JPEG", "PNG", "GIF", "BMP", "WBMP"
     * 
     * @param file
     *            文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadImageAndCrtThumbImage(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        return getResAccessUrl(storePath);
    }
 
    /**
     * 删除文件
     * 
     * @param fileUrl
     *            文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
        
        }
    }

}

api测试类:

package com.cxy.bean;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
@RestController
public class TestApi {

    
    @Resource
    private FastDFSClientWrapper fwc;
    
    /**
     * 图片上传
     * @param file
     * @return
     *
     * @author ZHANGJL
     * @dateTime 2018-02-24 15:49:48
     */
    @PostMapping("/uploadPic")
    public @ResponseBody String uploadPic(@RequestParam("file")MultipartFile file){
        Result<Map<String, String>> result = new Result<Map<String,String>>();
        try {
            Map<String, String> map = new HashMap<String, String>();
            //返回FastDFS配置好的图片路径
            String url = fwc.uploadFile(file);//正常上传
            String url1 = fwc.uploadImageAndCrtThumbImage(file);//小图
            map.put("max", url);
            map.put("min", url1);
            result.setCode(200);
            result.setContent(map);
        } catch (Exception e) {
            // TODO: handle exception
            
            result.setCode(400);
        }
        
        return JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue);
    }

}

postman测试:

将地址拼接:

就可以看如下结果.,

这个也可以为单独的文件上传服务,

猜你喜欢

转载自www.cnblogs.com/xiufengchen/p/10373200.html
0条评论
添加一条新回复