6

图床从SAE迁移到七牛

 2 years ago
source link: https://www.isaced.com/post-275.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

图床从SAE迁移到七牛

关于图床的又一次迁移·小记

最早博客用的国外一些支持外链的图床,担心速度和稳定性,后面利用 Migs 这个 PHP 小程序在 SAE 上搭建了一个图床,用了比较久,好一段时间前就想把SAE迁移到七牛,连图片上传脚本都写好了,一直没有对之前的图片做迁移,今天花了半天把迁移工作完成了。

迁移主要步骤如下:

  • 导出整个 Blog 数据库备份文件 (.sql)
  • 筛选出所有原 SAE 的图片 URL
  • 将所有原图下载到本地
  • 将所有下载到本地的原图批量上传到七牛的空间
  • 对 Blog 数据库备份文件批量替换 url 中的原SAE子域名到新的七牛子域名
  • 批量替换后的数据库备份文件上传到服务器还原

首先用 Swift 写了个简单的脚本把原有在 SAE 上的图片都下载到本地来:

//
//  main.swift
//  Download All Origin Image
//
//  Created by feeling on 16/3/16.
//
//

import Foundation

let fileName = "isaced.sql"

// 获取当前目录
let currentPath = NSString(string: NSFileManager.defaultManager().currentDirectoryPath)
print("Current Path:\(currentPath)")

// 源文件
let filePath = currentPath.stringByAppendingPathComponent(fileName)

// 从文件读取出字符串
let sql = try NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding)

// 正则
func matchesForRegexInText(regex: String!, text: String!) -> [String] {
    
    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

// 用正则表达式查找出所有原 SAE 的图片路径
let imageURList = matchesForRegexInText("[a-zA-z]+://isaced-img.stor.sinaapp.com[^\\s\\\\)']*", text: sql as String)

let downloadQueue = NSOperationQueue()
downloadQueue.maxConcurrentOperationCount = 3

var i = 0
for imageUrlString in imageURList {
    let downloadOperation = NSBlockOperation(block: { () -> Void in
        let imageName = (imageUrlString as NSString).lastPathComponent
        var imageData = NSData(contentsOfURL: NSURL(string: imageUrlString)!)
        var imageWritePath = currentPath.stringByAppendingPathComponent("download")
        imageWritePath = (imageWritePath as NSString).stringByAppendingPathComponent(imageName)
        imageData!.writeToFile(imageWritePath, atomically: true)
        
        print(imageName,i++)
    })
    downloadQueue.addOperation(downloadOperation)
}

// 加上这行保证不让程序提前结束
NSRunLoop.mainRunLoop().run()

全部下载到一个名为 download 的文件夹中,然后通过七牛后台管理的在线批量上传传到七牛空间,保持文件名和原来一致,只是域名部分变了。

然后用 SublimeText 将所有 URL 中原域名(isaced-img.stor.sinaapp.com) 批量替换成七牛的域名(isaced.qiniudn.com)

用 scp 命令把 SQL 文件上传到服务器:

scp -P 123 /block/isaced.sql [email protected]:/root/blog/isaced_qiniu_tran.sql

-P :服务器端口号,切记不是小写的 p

Mysql 还原就行了~

``` > mysql > use blog > source backup.sql


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK