天天看点

springcloud + FastDFS + 二维码

SpringCloud+二维码生成+FastDfs

1、引入依赖

<!--工具类-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
</dependency>
<!--二维码生成-->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
</dependency>
<!--上传编解码工具包-->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
</dependency>
<!-- 文件上传 -->
<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.27.2</version>
</dependency>
           

2、添加配置

info:
  fdfs:
    nginx: 172.22.1.21:8888
# 分布式文件系统FDFS配置
fdfs:
  soTimeout: 1500 #socket连接超时时长
  connectTimeout: 600 #连接tracker服务器超时时长
  web-server-url: http://${info.fdfs.nginx}/ #FDFS中的nginx的ip和port
  thumbImage: #缩略图生成参数,可选
    width: 150
    height: 150
  trackerList: #TrackerList参数,支持多个,我这里只有一个,如果有多个在下方加- x.x.x.x:port
    - 172.22.1.21:22122
  pool:
    max-total: 100
    max-wait-millis: 60
           

3、添加配置类

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

/**
 * 1.导入FastDFS-Client组件
 * 2.解决jmx重复注册bean的问题
 * @author 三多
 * @Time 2020/6/18
 */
@Configuration
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class FdfsConfiguration {
}

           

4、添加工具类

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件上传、QR生成
 * @author 三多
 * @Time 2020/6/18
 */
@Component
public class FastDfsUtil {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        String fullPath = storePath.getFullPath();
        getResAccessUrl(fullPath);
        return fullPath;

    }

    /**
     *
     * @param outputStream
     * @return
     * @throws IOException
     */
    public String uploadFile(ByteArrayOutputStream outputStream) throws IOException {

        // 调用FastDFS中的接口将数据流保存到服务器返回图片地址
        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(inputStream,inputStream.available(),ImgUtil.IMAGE_TYPE_PNG,null);
        return  this.getResAccessUrl(storePath.getFullPath());
    }

    /**
     * 获取上传文件完整路径
     *
     * @param file
     * @return
     */
    public String uploadFile(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            StorePath storePath = fastFileStorageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
            return storePath.getFullPath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 文件下载
     * file: /group1/M00/00/00/rBYBFV7rQ0CAVzsaAAAMvVtlKU8159.sql
     *
     * @param filePath
     * @return
     */
    public byte[] downloadFile(String filePath) {
        StorePath storePath = StorePath.parseFromUrl(filePath);
        byte[] bytes = fastFileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
        return bytes;
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    public Boolean deleteFile(String filePath) {
        if (StringUtils.isEmpty(filePath)) {
            return false;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(filePath);
            fastFileStorageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 封装文件完整URL地址
     *
     * @param path
     * @return
     */
    public String getResAccessUrl(String path) {
        String url = fdfsWebServer.getWebServerUrl() + path;
        System.out.println("上传文件地址为:\n" + url);
        return url;
    }

    /**
     * 根据内容生成二维码
     * @param content
     * @return
     */
    public String packageUrlForLink(String content) {
        BufferedImage image = QrCodeUtil.generate(content, 400, 400);
        String link = "";
        try {
            //以流的方式讲图片上传到fastdfs上:
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, ImgUtil.IMAGE_TYPE_PNG, outputStream);
            //commonFileUtil.upfileImage()的方式其实是调用的
            // fastFileStorageClient.uploadImageAndCrtThumbImage(is, size, fileExtName, metaData)的方法
            link = this.uploadFile(outputStream);
            System.out.println(link);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return link;
    }

}

           

4、controller

import com.smart.common.utils.upload.FastDfsUtil;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.apache.commons.io.IOUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.net.URLEncoder;
    
    /**
     * 文件上传
     *
     * @author 三多
     * @Time 2020/6/18
     */
    @Api("文件上传")
    @RestController
    @RequestMapping("/fastDfs")
    public class FastDfsController {
        /**
         * 导入工具类
         */
        @Autowired
        private FastDfsUtil fastDfsUtil;
    
        @ApiOperation("文件上传")
        @PostMapping("/upload")
        public void uploadFile(MultipartFile file) throws IOException {
            String s = fastDfsUtil.uploadFile(file);
            String resAccessUrl = fastDfsUtil.getResAccessUrl(s);
        }
    
        /**
         * @param content 源
         * @throws IOException
         */
        @ApiOperation("生成二维码并上传")
        @PostMapping("/qr/upload")
        public String uploadQrCodeFile(String content) throws IOException {
            return fastDfsUtil.packageUrlForLink(content);
        }
    
        @ApiOperation("文件下载")
        @GetMapping("/download")
        public void downloadFile(String filePath, HttpServletResponse response) throws IOException {
            byte[] bytes = fastDfsUtil.downloadFile(filePath);
            String fileName = "哈哈.jpg";
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            //方式一
            // fileName=new String(fileName.getBytes(), "ISO8859-1")
            //方式二
            fileName = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            IOUtils.write(bytes, response.getOutputStream());
        }
    
        /**
         * 流媒体的方式播放视频,只能从头看到尾,不能手动点击重新看已经看过的内容
         *
         * @param filePath
         * @param response
         * @throws IOException
         */
        @ApiOperation("播放视频")
        @GetMapping("/play")
        public void streamMedia(String filePath, HttpServletResponse response) throws IOException {
            byte[] bytes = fastDfsUtil.downloadFile(filePath);
            IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream());
            response.flushBuffer();
        }
    
        @ApiOperation("删除文件")
        @GetMapping("/delete")
        public void deleteFile(String filePath) {
            Boolean result = fastDfsUtil.deleteFile(filePath);
        }
    }
    
           

5、使用注解

参考

  1. java生成二维码并用fastdfs上传文件返回图片地址
  2. Java生成二维码并用FastDFS上传到文件服务器返回图片地址