forked from petter-gao/PicBed4MWeb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.js
55 lines (52 loc) · 1.35 KB
/
helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const axios = require('axios')
const fs = require('fs')
const config = require('./config.json')
const {repo, token} = config
const moment = require('moment');
moment.locale('zh-cn');
var log4js = require('log4js')
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'app.log', category: 'GithubPicBed' }
]
})
var log = log4js.getLogger('GithubPicBed')
/**
* @param {[String]} file {picture path}
* @return {[String]} {picture pid}
*/
async function getImgUrl(file){
if (repo.length == 0 || repo.length == 0)
throw 'config error'
try{
let bitmap = fs.readFileSync(file)
let base64Img = Buffer.from(bitmap).toString('base64')
let timestamp = moment().format('YYYYMMDDHHmmss')+'.jpg'
let imageUrl = 'https://api.github.com/repos/'+repo+'/contents/'+timestamp
let body = {
'branch': 'master',
'message': 'upload image',
'content': base64Img,
'path': timestamp,
}
let upImgResp = await axios.put(imageUrl, body, {
headers: {
'Authorization':'token '+token,
'Content-Type': 'application/json; charset=utf-8',
}
})
imgUrl = upImgResp.data['content']['download_url']
if (imgUrl) {
log.info('success upload a pic to: '+imgUrl)
return imgUrl
} else {
throw 'no img url '
}
}
catch(e){
log.error('upload failed with error: '+e)
throw 'no img url '
}
}
module.exports = getImgUrl