利用簡(jiǎn)書圖片上傳功能搭建快速免費(fèi)的圖床

之前在用 hexo搭建博客的時(shí)候一直想弄個(gè)圖床,在網(wǎng)上搜了許多方法都覺得不好。

后來發(fā)現(xiàn)簡(jiǎn)書的寫文章頁面可以上傳圖片,于是萌生了利用簡(jiǎn)書的圖片上傳功能來搭建一個(gè)圖床的想法。

下面是具體實(shí)現(xiàn),詳細(xì)的可以看代碼實(shí)現(xiàn),整體不是很難只要拿到 cookie然后上傳圖片即可。

關(guān)鍵代碼:

cookie:簡(jiǎn)書登錄之后的 cookie
filepath:要上傳圖片的絕對(duì)路徑,同目錄下可直接使用名字
filename:要上傳圖片的名字(隨意?。?/p>

def uploadImage(cookie, filepath, filename):
    upload_url = 'https://upload.qiniup.com/'
    token_url = 'http://www.itdecent.cn/upload_images/token.json?filename={}'.format(filename)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36',
        'Cookie': cookie,
    }

    response = requests.get(token_url, headers=headers)
    response.encoding = response.apparent_encoding
    token_and_key = json.loads(response.text)

    with open(filepath, 'rb') as file:
        files = {
            'file': (filename, file),
            'token': (None, token_and_key['token']),
            'key': (None, token_and_key['key']),
        }
        response = requests.post(upload_url, headers=headers, files=files)
        response.encoding = response.apparent_encoding
        return json.loads(response.text)['url']

PyQt4封裝后的代碼:

與腳本同目錄下創(chuàng)建一個(gè)名為 config的文件(沒有后綴名),用文本編輯器打開(別用記事本,如果用記事本打開并保存過請(qǐng)刪除重建),將簡(jiǎn)書登錄后的 cookie直接粘貼進(jìn)去(不需要多余的字符,只要 cookie就行)
代碼附上:

#-*- coding: utf-8 -*
__author__ = 'geebos'
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import requests
import json
import sys


class UploadBox(QDialog):
    def __init__(self):
        QDialog.__init__(self)

        layout = QVBoxLayout()

        self.data = {}
        self.cookie  = self.getCookie().strip()

        self.location_lable = QLabel("圖片位置:")
        self.url_lable = QLabel("圖片鏈接:")
        self.show_path = QLineEdit()
        self.show_result = QTextBrowser()
        self.select_button = QPushButton("選擇圖片")
        self.comfir_button = QPushButton("確認(rèn)上傳")

        layout.addWidget(self.location_lable)
        layout.addWidget(self.show_path)
        layout.addWidget(self.url_lable)
        layout.addWidget(self.show_result)
        layout.addWidget(self.select_button)
        layout.addWidget(self.comfir_button)

        self.setWindowTitle("圖片上傳")
        self.setLayout(layout)

        self.select_button.clicked.connect(self.selectFile)
        self.comfir_button.clicked.connect(self.uploadImage)

    def getCookie(self):
        try:
            with open('config', 'r') as f:
                return f.readline()
        except Exception:
            QMessageBox.warning(self, "提示", "配置文件 config出錯(cuò)")

    def selectFile(self):
        filepath = QFileDialog.getOpenFileName(self, caption="選擇圖片", directory='.', filter="ALL FILES (*.*)")
        self.show_path.setText(filepath)
        self.data['filepath'] = filepath

    def uploadImage(self):
        if 'filepath' in self.data:
            filepath = self.data['filepath']
            filename = filepath.split('/')[-1]
            print(filename)
        else:
            return

        upload_url = 'https://upload.qiniup.com/'
        token_url = 'http://www.itdecent.cn/upload_images/token.json?filename={}'.format(filename)
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36',
            'Cookie': self.cookie,
        }

        response = requests.get(token_url, headers=headers)
        response.encoding = response.apparent_encoding
        token_and_key = json.loads(response.text)

        if 'token' not in token_and_key:
            self.show_result.clear()
            QMessageBox.warning(self, "提示", "格式錯(cuò)誤,請(qǐng)選擇圖片")
            return

        with open(filepath, 'rb') as file:
            files = {
                'file': (filename, file), 'token': (None, token_and_key['token']), 'key': (None, token_and_key['key']),
            }
            response = requests.post(upload_url, headers=headers, files=files)
            response.encoding = response.apparent_encoding
            result = json.loads(response.text)

            if 'url' in result:
                self.show_result.clear()
                self.show_result.append(result['url'])
            else:
                self.show_result.clear()
                QMessageBox.Information(self, "提示", "上傳失敗,請(qǐng)檢查 cookie是否有效")


app = QApplication(sys.argv)
dialog = UploadBox()
dialog.show()
app.exec_()

pyinstaller生成的可執(zhí)行文件:

使用方法同腳本:
https://pan.baidu.com/s/1qFdVcttwZdRS97jFgXpKTA

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請(qǐng)求組件 FMDB本地?cái)?shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,196評(píng)論 3 119
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,939評(píng)論 25 709
  • 這一周有點(diǎn)特別,2017年倒數(shù)第二周,給momo絕育了- - 周一,捕捉到辦公室斗毆現(xiàn)場(chǎng) 兩位同事讓我仿佛回到了小...
    Gnoodle閱讀 685評(píng)論 15 11
  • 幼稚的孩子,真有意思! 自我意識(shí)需要不斷打破,所謂自我覺醒,不斷開疆?dāng)U土,你的世界才能與真正的三千世界重合,所謂見...
    縱情嬉戲天地間閱讀 319評(píng)論 0 0
  • 投射:1投射金邊房地產(chǎn)一切順利! 2投射認(rèn)識(shí)新客戶讓我終身致富! 3投射有新女朋友!感賞:1-感賞老師關(guān)心我! 2...
    謝奕鋒閱讀 193評(píng)論 0 0

友情鏈接更多精彩內(nèi)容