为什么使用bcakblaze B2

  • 免费,有10G的免费空间
  • API友好,支持s3 API
  • 带宽联盟。使用Cloudflare中转获取图片不计流量费用

怎么传图片就不赘述了,我用的是uPic,你可以用你喜欢的工具

使用bcakblaze B2

先注册,创建一个bucket

然后上传一张图(也可以配置使用你的工具上传,或者网页上传),然后记录如下信息

  1. Bucket Name
  2. Friendly URL里面的host

使用Cloudflare Workers

为什么使用wokers而不用cname的方式接入

  • 去除URL中的 /file/ 部分
  • 去除一些从 Backblaze B2 响应的无用请求头
  • 加上基本的 CORS 请求头,以便允许图片嵌入到网站中
  • 为图片优化缓存 (浏览器的缓存, 以及 CDN 边界服务器上的缓存)

先创建一个workers,然后写入如下脚本,只需要修改2个变量

  1. b2Bucket -> 上述1
  2. b2Domain -> 上述2
'use strict';
const b2Domain = 'f004.backblazeb2.com'; // configure this as per instructions above
const b2Bucket = 'bucketName'; // configure this as per instructions above
const b2UrlPath = `/file/${b2Bucket}/`;
addEventListener('fetch', event => {
	return event.respondWith(fileReq(event));
});

// define the file extensions we wish to add basic access control headers to
const corsFileTypes = ['png', 'jpg', 'gif', 'jpeg', 'webp'];

// backblaze returns some additional headers that are useful for debugging, but unnecessary in production. We can remove these to save some size
const removeHeaders = [
	'x-bz-content-sha1',
	'x-bz-file-id',
	'x-bz-file-name',
	'x-bz-info-src_last_modified_millis',
	'X-Bz-Upload-Timestamp',
	'x-bz-server-side-encryption',
	'x-bz-client-unauthorized-to-read',
	'Expires'
];
const expiration = 31536000; // override browser cache for images - 1 year

// define a function we can re-use to fix headers
const fixHeaders = function(url, status, headers){
	let newHdrs = new Headers(headers);
	// add basic cors headers for images
	if(corsFileTypes.includes(url.pathname.split('.').pop())){
		newHdrs.set('Access-Control-Allow-Origin', '*');
	}
	// override browser cache for files when 200
	if(status === 200){
		newHdrs.set('Cache-Control', "public, max-age=" + expiration);
	}else{
		// only cache other things for 5 minutes
		newHdrs.set('Cache-Control', 'public, max-age=300');
	}
	// set ETag for efficient caching where possible
	const ETag = newHdrs.get('x-bz-content-sha1') || newHdrs.get('x-bz-info-src_last_modified_millis') || newHdrs.get('x-bz-file-id');
	if(ETag){
		newHdrs.set('ETag', ETag);
	}
	// remove unnecessary headers
	removeHeaders.forEach(header => {
		newHdrs.delete(header);
	});
	return newHdrs;
};

async function fileReq(event){
	const cache = caches.default; // Cloudflare edge caching
	const url = new URL(event.request.url);
	if(!url.pathname.startsWith(b2UrlPath)){ 
		url.pathname = b2UrlPath + url.pathname;
        // console.log(url.pathname);
	}
    url.host = b2Domain;
    // console.log(url);
	let response = await cache.match(url); // try to find match for this request in the edge cache
	if(response){
		// use cache found on Cloudflare edge. Set X-Worker-Cache header for helpful debug
		let newHdrs = fixHeaders(url, response.status, response.headers);
		newHdrs.set('X-Worker-Cache', "true");
		return new Response(response.body, {
			status: response.status,
			statusText: response.statusText,
			headers: newHdrs
		});
	}
	// no cache, fetch image, apply Cloudflare lossless compression
	response = await fetch(url, {cf: {polish: "lossless"}});
	let newHdrs = fixHeaders(url, response.status, response.headers);

  if(response.status === 200){

    response = new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: newHdrs
    });
  }else{
    response = new Response('File not found!', { status: 404 })
  }

	event.waitUntil(cache.put(url, response.clone()));
	return response;
}

脚本参考
https://blog.meow.page/archives/free-personal-image-hosting-with-backblaze-b2-and-cloudflare-workers/
https://jross.me/free-personal-image-hosting-with-backblaze-b2-and-cloudflare-workers/

我在脚本上的修改是把b2Domain改为b2的host,这样脚本更容易理解一些。

最后你可以使用自己的域名做一个route就可以使用自己的域名,cf workers的域名在国内墙的比较厉害...

推荐一个图片网站

https://unsplash.com