spring项目将生成的二维码上传至文件服务器

项目中将生成的二维码上传至文件服务器

二维码生成(InputStream 格式

 public static InputStream encode(String content, String logoPath, boolean needCompress) throws Exception {
    BufferedImage image = QrCodeUtil.createImage(content, logoPath, needCompress);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageIO.write(image, FORMAT, outputStream);
    //String streamEncoded = Base64Util.encode(outputStream.toByteArray());
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    return inputStream;
}

1.添加依赖


      com.github.tobato
      fastdfs-client
      1.25.4-RELEASE

2.调用类

@Slf4j
@Service
public class FileServiceImpl implements FileService {

@Autowired
private FastFileStorageClient fastFileStorageClient;

/**
 * 文件服务器地址
 */
@Value("${fast.dfs.server}")
private String fastDFSServer;

@Override
public String  upload(InputStream inputStream) {
    StorePath storePath = new StorePath();
    String url = "";
    try {
        storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(inputStream, inputStream.available() , QrCodeUtil.FORMAT, null);
        url = fastDFSServer+storePath.getFullPath();
    } catch (Exception e) {
        log.error("upload file error:{}", e);
    }
    return url;
}

注:

  • storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(inputStream,
    inputStream.available() , “png”, null);

    inputStream 上传内容(以二进制流的格式)
    inputStream.available() (二进制流的文件大小)
    png(生成文件的格式)
    
  • fastDFSServer为上传文件服务器的ip(必须在配置文件中配置)

  • 返回的url 可通过浏览器访问,获取到上传文件的具体内容

3.在启动类中添加如下配置

@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)

4.在配置环境中配置:

#socket连接超时时长
fdfs.soTimeout = 300
#连接tracker服务器超时时长
fdfs.connect-timeout = 600
#TrackerList参数
fdfs.tracker-list[0] = 10.*.*.*:22122
#连接池最大连接数
fdfs.pool.max-total = 100
#连接池连接等待时间
fdfs.pool.max-wait-millis = 60
#fastDFSServer
fast.dfs.server = http://10.*.*.*:8888/

遇到问题:

required a bean of type ‘com.github.tobato.fastdfs.service.FastFileStorageClient’ that could not be found.

原因:Spring boot自动扫描注解只能扫描启动类所在的包及其子包,而通常情况下外部引用的jar包都不会在启动类的子包中,所以无法扫描到

解决:在启动类中添加

@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)

你可能感兴趣的:(工作常用,spring)