天天看點

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上傳到檔案伺服器傳回圖檔位址