solo 博客 - 七牛云改腾讯云图床(对象存储)

本贴最后更新于 2142 天前,其中的信息可能已经事过境迁

solo 博客 - 七牛云改腾讯云图床(对象存储)

  • solo 默认提供七牛云的对象存储,跑去注册发现还要实名,真麻烦。。 腾讯云估计大家都实名过了,那顺便就可以用了

  • 首先去 github 把 solo 博客源码 clone 到本地

https://github.com/b3log/solo

1.在数据库里插入几个数据

INSERT INTO `solo`.`b3_solo_option`(`oId`, `optionValue`, `optionCategory`) VALUES ('qcloudBucket', 'aliciz-123', 'qcloud');
INSERT INTO `solo`.`b3_solo_option`(`oId`, `optionValue`, `optionCategory`) VALUES ('qcloudDomain', 'https://www.aliciz.com', 'qcloud');
INSERT INTO `solo`.`b3_solo_option`(`oId`, `optionValue`, `optionCategory`) VALUES ('qcloudRegion', 'ap-guangzhou', 'qcloud');
INSERT INTO `solo`.`b3_solo_option`(`oId`, `optionValue`, `optionCategory`) VALUES ('qcloudSecretId', 'AKIDBgsgdsgm113424WX', 'qcloud');
INSERT INTO `solo`.`b3_solo_option`(`oId`, `optionValue`, `optionCategory`) VALUES ('qcloudSecretKey', 'sjfoijafSASAFAASFA', 'qcloud');

imagepng

至于这几个东西什么意思,可以看看腾讯云文档

链接:腾讯云-对象存储-基本概念

2.新增一个配置类

package org.b3log.solo.model;

public class QCloudOption {

  /**
  * 腾讯云-对象存储
  */
  public static final String CATEGORY_C_QCLOUD = "qcloud";
  public static final String ID_C_QCLOUD_REGION = "qcloudRegion";
  public static final String ID_C_QCLOUD_SECRET_ID = "qcloudSecretId";
  public static final String ID_C_QCLOUD_SECRET_KEY = "qcloudSecretKey";
  public static final String ID_C_QCLOUD_DOMAIN = "qcloudDomain";
  public static final String ID_C_QCLOUD_BUCKET = "qcloudBucket";
}

3.修改 controller

修改这个方法 org.b3log.solo.processor.FileUploadProcessor.uploadFile()


//前面省略 ... 

  wwAuth auth;
  UploadManager uploadManager = null;
  String uploadToken = null;
  JSONObject qiniu = null;
  JSONObject qcloud = null;
  COSClient cosClient = null;
  final String date = DateFormatUtils.format(System.currentTimeMillis(), "yyyy/MM");
  if (QN_ENABLED) {
//            try {
//                final BeanManager beanManager = BeanManager.getInstance();
//                final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class);
//                qiniu = optionQueryService.getOptions(Option.CATEGORY_C_QINIU);
//                if (null == qiniu) {
//                    final String msg = "Qiniu settings failed, please visit https://hacpai.com/article/1442418791213 for more details";
//                    LOGGER.log(Level.ERROR, msg);
//                    context.renderMsg(msg);
//
//                    return;
//                }
//
//                auth = Auth.create(qiniu.optString(Option.ID_C_QINIU_ACCESS_KEY), qiniu.optString(Option.ID_C_QINIU_SECRET_KEY));
//                uploadToken = auth.uploadToken(qiniu.optString(Option.ID_C_QINIU_BUCKET), null, 3600 * 6, null);
//                uploadManager = new UploadManager(new Configuration());
//            } catch (final Exception e) {
//                final String msg = "Qiniu settings failed, please visit https://hacpai.com/article/1442418791213 for more details";
//                LOGGER.log(Level.ERROR, msg);
//                context.renderMsg(msg);
//
//                return;
//            }
  final BeanManager beanManager = BeanManager.getInstance();
  final OptionQueryService optionQueryService = beanManager.getReference(OptionQueryService.class);

  qcloud = optionQueryService.getOptions(QCloudOption.CATEGORY_C_QCLOUD);
  COSCredentials cred = new BasicCOSCredentials(qcloud.optString(QCloudOption.ID_C_QCLOUD_SECRET_ID), qcloud.optString(QCloudOption.ID_C_QCLOUD_SECRET_KEY));
  ClientConfig clientConfig = new ClientConfig(new Region(qcloud.optString(QCloudOption.ID_C_QCLOUD_REGION)));
  cosClient = new COSClient(cred, clientConfig);

  }

  for (int i = 0; i < files.length; i++) {
	  final FileUpload file = files[i];
	  String originalName = fileName = file.getHeader().getFileName();
	  originalName = originalName.replaceAll("\\W", "");
	  try {
		  String suffix = StringUtils.substringAfterLast(fileName, ".");
		  final String contentType = file.getHeader().getContentType();
		  if (StringUtils.isBlank(suffix)) {
			  String[] exts = MimeTypes.findExtensionsByMimeTypes(contentType, false);
			  if (null != exts && 0 < exts.length) {
				  suffix = exts[0];
			  } else {
				  suffix = StringUtils.substringAfter(contentType, "/");
			  }
		  }

		  final String name = StringUtils.substringBeforeLast(fileName, ".");
		  final String processName = name.replaceAll("\\W", "");
		  final String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		  fileName = uuid + '_' + processName + "." + suffix;

		  if (QN_ENABLED) {
			  fileName = "file/" + date + "/" + fileName;
			  if (!ArrayUtils.isEmpty(names)) {
				  fileName = names[i];
			  }
			  // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
			  String bucketName = qcloud.optString(QCloudOption.ID_C_QCLOUD_BUCKET);
			  ObjectMetadata objectMetadata = new ObjectMetadata();
			  objectMetadata.setContentLength(file.getFileContent().length);
			  objectMetadata.setContentType(contentType.trim());
			  PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getFileInputStream(), objectMetadata);
			  putObjectRequest.setStorageClass(StorageClass.Standard);
			  PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

			  cosClient.shutdown();
			  succMap.put(originalName, qcloud.optString(QCloudOption.ID_C_QCLOUD_DOMAIN) + "/" + fileName);
  //                        uploadManager.put(file.getFileInputStream(), fileName, uploadToken, null, contentType);
  //                        succMap.put(originalName, qiniu.optString(Option.ID_C_QINIU_DOMAIN) + "/" + fileName);
		  } else {
			  try (final OutputStream output = new FileOutputStream(Solos.UPLOAD_DIR_PATH + fileName);
				   final InputStream input = file.getFileInputStream()) {
				  IOUtils.copy(input, output);
			  }
			  succMap.put(originalName, Latkes.getServePath() + "/upload/" + fileName);
		  }
	  } catch (final Exception e) {
		  LOGGER.log(Level.WARN, "Uploads file failed", e);

		  errFiles.add(originalName);
	  }
  }
  
//省略部分代码 ..

4.修改 nginx.conf

server {
        listen 443;
        server_name  www.aliciz.com;

        location ^~ /file/ {
            proxy_pass https://bucket-name.cos.ap-guangzhou.myqcloud.com;
        }

}

这样就完成啦,记得源码打包替换的时候,把原有的服务器配置备份一下。
其实 solo 在处理这个文件上传的地方可以再写得扩展性更强一些,这样就可以切换多家云服务厂商

  • Solo

    Solo 是一款小而美的开源博客系统,专为程序员设计。Solo 有着非常活跃的社区,可将文章作为帖子推送到社区,来自社区的回帖将作为博客评论进行联动(具体细节请浏览 B3log 构思 - 分布式社区网络)。

    这是一种全新的网络社区体验,让热爱记录和分享的你不再感到孤单!

    1433 引用 • 10052 回帖 • 484 关注
  • 存储
    21 引用 • 28 回帖 • 1 关注
  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3186 引用 • 8212 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • 88250 1

    v2.9.8 已经加入了多家 OSS 支持,开发方面可以进行扩展,目前支持七牛云和阿里云,欢迎贡献代码 :)

  • someone

    评论测试😄

  • someone

    😂