使用python将图像上传到ima​​gekit

时间:2019-03-13 09:44:07

标签: rest image-upload imagekit

我正在尝试为imagekit构建批量图像上传脚本。 缺少文档,文档上的cURL示例不起作用:

https://docs.imagekit.io/?shell#server-side-image-upload

到目前为止,我最接近的尝试是开发一种与显示图片列表并删除它们类似的调用结构(将其删除也是一种后期请求)(

import os
import hmac
import time
import base64
import requests
from hashlib import sha1


def create_signature(api_key, string):
    string_to_sign = string.encode('utf-8')
    hashed = hmac.new(api_key, string_to_sign, sha1)
    return hashed.hexdigest()


def get_file(file_name):
    open_file = open(file_name)
    encoded = base64.b64encode(open_file.read())
    encoded_file = open_file
    #open_file.close()
    return encoded_file



api_key = 'my_api_key='
imagekit_id = 'my_imagekit_id'
file_path = '1_test'

url = 'https://upload.imagekit.io/rest/api/image/v2/{0}'.format(imagekit_id)
files = os.listdir(file_path)
for file in files:
    file_name = file_path + '/' + file
    timestamp = int(time.time())
    string = 'apiKey={0}&filename={1}&timestamp={2}'.format(api_key, file_name, timestamp)
    signed_key = create_signature(api_key, string)
    encoded_file = get_file(file_name)
    headers = {
        'Content-Type': "Content - Type: multipart / form - data"
    }
    payload = {'apiKey': api_key, 'filename': file_name,
              'timestamp': timestamp, 'signature': signed_key,
              'file': encoded_file}

    r = requests.post(url, data=payload, headers=headers)
    encoded_file.close()

状态码= 400,出现以下错误:

>>> r._content
'{"exception":true,"statusNumber":1400,"statusCode":"BAD_REQUEST","message":"File not found for upload"}'

0 个答案:

没有答案