Parcourir la source

Better handling of image upload

master
David Larlet il y a 4 ans
Parent
révision
79e4ee8eb1
Aucune clé connue n'a été trouvée dans la base pour cette signature
3 fichiers modifiés avec 45 ajouts et 3 suppressions
  1. 2
    1
      js/upload_images_controller.js
  2. 2
    0
      requirements.txt
  3. 41
    2
      server.py

+ 2
- 1
js/upload_images_controller.js Voir le fichier

@@ -40,11 +40,12 @@ application.register(

if (isOversized) {
this.outputTarget.classList.add('oversized')
this.outputTarget.innerText = `Oversized!`
this.outputTarget.innerText = 'Oversized!'
this.inputTarget.value = ''
return
} else {
this.outputTarget.classList.remove('oversized')
this.outputTarget.innerText = ''
this.dropzoneTarget.classList.add('hidden')
}


+ 2
- 0
requirements.txt Voir le fichier

@@ -1 +1,3 @@
filetype==1.0.5
roll==0.11.0
Wand==0.5.8

+ 41
- 2
server.py Voir le fichier

@@ -1,11 +1,31 @@
import glob
import mimetypes
import random
import string
from http import HTTPStatus
from pathlib import Path

import filetype
from roll import Roll
from roll.extensions import simple_server, static
from wand.exceptions import MissingDelegateError
from wand.image import Image

app = Roll()
static(app)
upload_path = Path("uploaded_images")


def _get_random_filename():
random_string = "".join(
random.choices(
string.ascii_lowercase + string.digits + string.ascii_uppercase, k=15
)
)
file_exists = len(glob.glob(f"{upload_path}/{random_string}.*")) > 0
if file_exists:
return _get_random_filename()
return random_string


@app.route("/")
@@ -18,8 +38,27 @@ async def home(request, response):
async def upload_images(request, response):
images = request.files.list("images")
for image in images:
filepath = Path("uploaded_images") / image.filename
filepath.write_bytes(image.read())
random_string = _get_random_filename()
tmp_filepath = Path("/tmp/") / random_string
tmp_filepath.write_bytes(image.read())
output_type = filetype.guess_extension(str(tmp_filepath))
error = None

try:
with Image(filename=tmp_filepath) as img:
img.strip()
with img.convert(output_type) as converted:
output_filename = f"{random_string}.{output_type}"
output_path = upload_path / output_filename
if output_type not in ["gif"]:
converted.sequence = [converted.sequence[0]]
converted.save(filename=str(output_path))
except MissingDelegateError:
error = "Invalid Filetype"
finally:
if tmp_filepath.exists():
tmp_filepath.unlink()
# TODO: deal with errors!
response.status = HTTPStatus.FOUND
response.headers["Location"] = "/"


Chargement…
Annuler
Enregistrer