使用七牛接口實現圖片和文件一鍵上傳
阿新 • • 發佈:2018-07-31
準備 末尾 文件 pip 同學 filepath ini star pytho 本文主要介紹使用七牛提供的接口把七牛雲作為圖床,用 Python 實現圖片上傳和文件上傳的腳本實現,可以支持按文件夾批量上傳。
搭建過網站的同學,一定都涉及到圖片上傳和文件上傳的問題,最近為了弄圖片資源接觸了一下雲存儲,還挺挺好用。
之前如果我們把圖片資源存儲到本機服務器,那就每次寫文章的時候都需要準備一堆的圖片,並且要上傳到對應的相對目錄上去,如果用了雲存儲(不限七牛),好處就是需要的資源直接上傳,然後生成一個鏈接來使用就行了,Markdown 語法對鏈接的支持也很好,恩,可以搞一下。
不過,又有了新問題,就是是用雲存儲,得先經過登錄->打開對象存儲->打開內容管理->上傳,然後填入上傳後的相對目錄,並手動選擇本地文件,是不是很麻煩?
所以本次是提供了一個一鍵上傳資源的腳本(僅針對七牛雲),實現的效果就是,輸入項目目錄和文件本地地址後,自動上傳所有文件到雲端,並生成可使用 URL。
來,直接上代碼:
# -*- coding: utf-8 -*- import os import sys from qiniu import Auth, put_file if 3 != len(sys.argv): print(‘[Usage] %s [dir_set] [filepath]‘ % os.path.basename(sys.argv[0])) sys.exit(0) else: # dir_set 的格式為 image/upload-qiniu/ ,註意末尾帶反斜杠/ dir_set = sys.argv[1] file_path = sys.argv[2] # 個人中心->密匙管理->AK access_key = ‘你的AccessKey‘ # 個人中心->密匙管理->SK secret_key = ‘你的SecretKey‘ # 七牛空間名 bucket_name = ‘你的存儲空間名‘ qiniu_auth = Auth(access_key, secret_key) def upload_qiniu(input_path): #upload single file to qiniu filename = os.path.basename(input_path) key = ‘%s%s‘ % (dir_set, filename) token = qiniu_auth.upload_token(bucket_name, key) ret, info = put_file(token, key, input_path, check_crc=True) if ret and ret[‘key‘] == key: print(‘%s done‘ % (‘http://www.sylan215.com/‘ + dir_set + filename)) else: print(‘%s error‘ % (‘http://www.sylan215.com/‘ + dir_set + filename)) def upload_all_files(input_path): if os.path.isfile(input_path): upload_qiniu(input_path) elif os.path.isdir(input_path): dirlist = os.walk(input_path) for root, dirs, files in dirlist: for filename in files: upload_qiniu(os.path.join(root, filename)) else: print(‘Please input the exists file path!‘) if __name__ == "__main__": upload_all_files(file_path)
使用說明
1. 請先安裝 qiniu 的依賴庫:
python -m pip install qiniu
2. 修改綁定域名
修改代碼中的 http://www.sylan215.com 為自己在七牛雲存儲綁定的域名
3. 帶兩個參數執行腳本
第一個參數是上傳後的目錄,第二個參數是文件在本地的地址,支持文件夾。
其中第一個參數的目錄格式為:image/test/。
比如如下的命令:
upload_to_qiniu.py image/test/ d:\test.png
運行後,上傳後的文件地址就類似:http://www.sylan215.com/image/test/test.png
PS:已使用 Python2.7 和 Python3.4 親測有效,其他 Python 版本如果有異常,請反饋。
更詳細的說明請跳轉到項目地址:https://github.com/sylan215/upload-to-qiniu,歡迎大家 star,並一起豐富這個腳本的功能。
使用七牛接口實現圖片和文件一鍵上傳