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

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

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

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 在处理这个文件上传的地方可以再写得扩展性更强一些,这样就可以切换多家云服务厂商

  • B3log

    B3log 是一个开源组织,名字来源于“Bulletin Board Blog”缩写,目标是将独立博客与论坛结合,形成一种新的网络社区体验,详细请看 B3log 构思。目前 B3log 已经开源了多款产品:PipeSoloSymWide 等,欢迎大家加入,贡献开源。

    2818 引用 • 4207 回帖 • 644 关注
  • Solo

    Solo 是一款小而美的 Java 博客系统,通过一个命令就可以启动使用。

    410 引用 • 3438 回帖 • 700 关注
  • 存储
    18 引用 • 34 回帖
  • Java

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

    2088 引用 • 6943 回帖 • 1121 关注
感谢    关注    收藏    赞同    反对    举报    分享