Never too late to learn.

0%

使用Python脚本批量上传文件至七牛

直接上代码

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#! /usr/bin/python
# -*- coding: utf-8 -*-
# flake8: noqa

from qiniu import Auth, put_file, etag, urlsafe_base64_encode
import qiniu.config
from qiniu import BucketManager
import sys, os, time
import subprocess
#import tinify

access_key = 'access key'
secret_key = 'secret key'
bucket_name = 'your bucket name'
bucket_url = 'bucket_url'
md_url_result = "md_url.md"

img_suffix = ["JPG", "PNG", "jpg", "jpeg", "png", "bmp", "gif"]

def getFilesList(path):
fileList = []
files = os.listdir(path)
for f in files:
if (os.path.isfile(f)):
#添加文件
fileList.append(f)
return fileList

def upload_img(bucket_name, file_name, file_path):
# generate upload token
token = q.upload_token(bucket_name, file_name, 3600)
ret, info = put_file(token, file_name, file_path)
print "feedback info:"
print(info)
assert ret['key'] == file_name
assert ret['hash'] == etag(file_path)

# delete local imgFile
# os.remove(file_path)
return

def get_img_url(bucket_url, file_name):
img_url = 'http://%s/%s' % (bucket_url, file_name)
# generate md_url
md_url = file_name + ":\n![%s](%s-JPG)\n" % (file_name, img_url)
return md_url

def save_url_to_txt(bucket_url, file_name):
img_url = 'http://%s/%s' % (bucket_url, file_name)
# generate md_url
md_url = file_name + ":\n![%s](%s-JPG)\n" % (file_name, img_url)
# save to clip board
add2ClipBoard(md_url)
# save md_url to txt
with open(md_url_result, "a") as f:
f.write(md_url)
return

def add2ClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)


if __name__ == '__main__':
print sys.path[0]
print sys.argv[0] #file name

if len(sys.argv) == 1:
print("drag files here to upload ...")
#sys.exit(0)
files = getFilesList("./")
else:
files = sys.argv[1:]

#构建鉴权对象
q = Auth(access_key, secret_key)
# bucket = BucketManager(q)

#timeStr = getTimeStr()

for file in files:
if os.path.isdir(file):
print "暂不支持上传目录:", file
#sys.exit(0)
if os.path.isfile(file):
suffix = os.path.splitext(file)[1][1:] # 扩展名
prefix = "blog/windowsSoftware/" if suffix in img_suffix else "file/"
name = os.path.split(file)[1] #文件名
up_filename = prefix + name
print "\nupload:" , up_filename, time.strftime("%Y/%m/%d/%X", time.localtime())
# os.remove(img)
upload_img(bucket_name, up_filename, file)
save_url_to_txt(bucket_url, up_filename)

参考资料:

七牛Python SDK

拖曳文件上传到七牛的Python脚本

markdown helper

Coffee? ☕