I want to upload to Imgur an image that was uploaded to my Flask app. Currently, I save the uploaded file to a temporary file then pass the filename to upload_image
. Is there a simpler way that avoids the temporary file?
def upload_image():
file = request.files['file']
filename = secure_filename(file.filename)
target_path = os.path.join(UPLOAD_FOLDER, filename)
file.save(target_path)
im = pyimgur.Imgur(IMGUR_CLIENT_ID)
uploaded_image = im.upload_image(target_path, title=filename)
os.remove(target_path)
return uploaded_image.link
PyImgur only supports passing a filename to upload_image
. If it supported passing a file object, you could pass the uploaded file directly to it.
You can use the PyImgur client but build the request yourself. Just do what upload_image
does internally except use the uploaded file directly.
from base64 import b64encode
data = b64encode(request.files['file'].read())
client = pyimgur.Imgur(IMGUR_CLIENT_ID)
r = client._send_request('https://api.imgur.com/3/image', method='POST', params={'image': data})
return r['link']