|
| 1 | +#!flask/bin/python |
| 2 | + |
| 3 | +# Author: Ngo Duy Khanh |
| 4 | +# Email: ngokhanhit@gmail.com |
| 5 | +# Git repository: https://github.com/ngoduykhanh/flask-file-uploader |
| 6 | +# This work based on jQuery-File-Upload which can be found at https://github.com/blueimp/jQuery-File-Upload/ |
| 7 | + |
| 8 | +import os |
| 9 | +import PIL |
| 10 | +from PIL import Image |
| 11 | +import simplejson |
| 12 | +import traceback |
| 13 | + |
| 14 | +from flask import Flask, request, render_template, redirect, url_for, send_from_directory |
| 15 | +from flask_bootstrap import Bootstrap |
| 16 | +from werkzeug.utils import secure_filename |
| 17 | + |
| 18 | +from lib.upload_file import uploadfile |
| 19 | + |
| 20 | + |
| 21 | +app = Flask(__name__) |
| 22 | +app.config['SECRET_KEY'] = 'hard to guess string' |
| 23 | +app.config['UPLOAD_FOLDER'] = 'data/' |
| 24 | +app.config['THUMBNAIL_FOLDER'] = 'data/thumbnail/' |
| 25 | +app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 |
| 26 | + |
| 27 | +ALLOWED_EXTENSIONS = set(['txt', 'gif', 'png', 'jpg', 'jpeg', 'bmp', 'rar', 'zip', '7zip', 'doc', 'docx']) |
| 28 | +IGNORED_FILES = set(['.gitignore']) |
| 29 | + |
| 30 | +bootstrap = Bootstrap(app) |
| 31 | + |
| 32 | + |
| 33 | +def allowed_file(filename): |
| 34 | + return '.' in filename and \ |
| 35 | + filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS |
| 36 | + |
| 37 | + |
| 38 | +def gen_file_name(filename): |
| 39 | + """ |
| 40 | + If file was exist already, rename it and return a new name |
| 41 | + """ |
| 42 | + |
| 43 | + i = 1 |
| 44 | + while os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], filename)): |
| 45 | + name, extension = os.path.splitext(filename) |
| 46 | + filename = '%s_%s%s' % (name, str(i), extension) |
| 47 | + i += 1 |
| 48 | + |
| 49 | + return filename |
| 50 | + |
| 51 | + |
| 52 | +def create_thumbnail(image): |
| 53 | + try: |
| 54 | + base_width = 80 |
| 55 | + img = Image.open(os.path.join(app.config['UPLOAD_FOLDER'], image)) |
| 56 | + w_percent = (base_width / float(img.size[0])) |
| 57 | + h_size = int((float(img.size[1]) * float(w_percent))) |
| 58 | + img = img.resize((base_width, h_size), PIL.Image.ANTIALIAS) |
| 59 | + img.save(os.path.join(app.config['THUMBNAIL_FOLDER'], image)) |
| 60 | + |
| 61 | + return True |
| 62 | + |
| 63 | + except: |
| 64 | + # print traceback.format_exc() |
| 65 | + return False |
| 66 | + |
| 67 | + |
| 68 | +@app.route("/upload", methods=['GET', 'POST']) |
| 69 | +def upload(): |
| 70 | + if request.method == 'POST': |
| 71 | + files = request.files['file'] |
| 72 | + |
| 73 | + if files: |
| 74 | + filename = secure_filename(files.filename) |
| 75 | + filename = gen_file_name(filename) |
| 76 | + mime_type = files.content_type |
| 77 | + |
| 78 | + if not allowed_file(files.filename): |
| 79 | + result = uploadfile(name=filename, type=mime_type, size=0, not_allowed_msg="File type not allowed") |
| 80 | + |
| 81 | + else: |
| 82 | + # save file to disk |
| 83 | + uploaded_file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) |
| 84 | + files.save(uploaded_file_path) |
| 85 | + |
| 86 | + # create thumbnail after saving |
| 87 | + if mime_type.startswith('image'): |
| 88 | + create_thumbnail(filename) |
| 89 | + |
| 90 | + # get file size after saving |
| 91 | + size = os.path.getsize(uploaded_file_path) |
| 92 | + |
| 93 | + # return json for js call back |
| 94 | + result = uploadfile(name=filename, type=mime_type, size=size) |
| 95 | + |
| 96 | + return simplejson.dumps({"files": [result.get_file()]}) |
| 97 | + |
| 98 | + if request.method == 'GET': |
| 99 | + # get all file in ./data directory |
| 100 | + files = [f for f in os.listdir(app.config['UPLOAD_FOLDER']) if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'],f)) and f not in IGNORED_FILES ] |
| 101 | + |
| 102 | + file_display = [] |
| 103 | + |
| 104 | + for f in files: |
| 105 | + size = os.path.getsize(os.path.join(app.config['UPLOAD_FOLDER'], f)) |
| 106 | + file_saved = uploadfile(name=f, size=size) |
| 107 | + file_display.append(file_saved.get_file()) |
| 108 | + |
| 109 | + return simplejson.dumps({"files": file_display}) |
| 110 | + |
| 111 | + return redirect(url_for('index')) |
| 112 | + |
| 113 | + |
| 114 | +@app.route("/delete/<string:filename>", methods=['DELETE']) |
| 115 | +def delete(filename): |
| 116 | + file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) |
| 117 | + file_thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'], filename) |
| 118 | + |
| 119 | + if os.path.exists(file_path): |
| 120 | + try: |
| 121 | + os.remove(file_path) |
| 122 | + |
| 123 | + if os.path.exists(file_thumb_path): |
| 124 | + os.remove(file_thumb_path) |
| 125 | + |
| 126 | + return simplejson.dumps({filename: 'True'}) |
| 127 | + except: |
| 128 | + return simplejson.dumps({filename: 'False'}) |
| 129 | + |
| 130 | + |
| 131 | +# serve static files |
| 132 | +@app.route("/thumbnail/<string:filename>", methods=['GET']) |
| 133 | +def get_thumbnail(filename): |
| 134 | + return send_from_directory(app.config['THUMBNAIL_FOLDER'], filename=filename) |
| 135 | + |
| 136 | + |
| 137 | +@app.route("/data/<string:filename>", methods=['GET']) |
| 138 | +def get_file(filename): |
| 139 | + return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER']), filename=filename) |
| 140 | + |
| 141 | + |
| 142 | +@app.route('/', methods=['GET', 'POST']) |
| 143 | +def index(): |
| 144 | + return render_template('file_upload/index.html') |
| 145 | + |
| 146 | + |
| 147 | + |
| 148 | +if __name__ == '__main__': |
| 149 | + app.run(debug=True) |
0 commit comments