Jelajahi Sumber

Improve image upload and view

JoostSijm 6 tahun lalu
induk
melakukan
c28bcf2985

+ 12 - 0
app/models.py

@@ -12,6 +12,8 @@ from flask_login import UserMixin
 from app import db, argon2, login_manager
 
 
+ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
+
 page_file = db.Table(
     'page_file',
     db.Column(
@@ -115,6 +117,16 @@ class File(db.Model):
     path = db.Column(db.String, nullable=False)
     identifier = db.Column(db.String) 
 
+    def extension(self):
+        """Return file extension"""
+        return '.' in self.path and self.path.rsplit('.', 1)[1].lower()
+
+
+    def is_image(self):
+        """True if file is image"""
+        return self.extension() in ALLOWED_EXTENSIONS
+
+
     user_id = db.Column(
         db.Integer,
         db.ForeignKey("user.id")

+ 6 - 2
app/modules/backend/modules/file/app.py

@@ -43,14 +43,18 @@ def create():
             file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
 
             db_file = File()
-            db_file.title = request.form['title']
+            if request.form['title']:
+                title = request.form['title'] 
+            else:
+                title = file.filename
+            db_file.title = title 
             db_file.user_id = current_user.id
             db_file.path = file.filename
 
             db.session.add(db_file)
             db.session.commit()
 
-            flash('File "%s" successfully uploaded' % file.filename, 'success')
+            flash('File "%s" successfully uploaded' % db_file.title, 'success')
 
     return render_template('file/create.j2')
 

+ 5 - 1
app/modules/backend/modules/file/templates/file/view.j2

@@ -3,5 +3,9 @@
 <h1>Title: {{ file.title }}</h1>
 <a href="{{ url_for('backend_file.edit', file_id=file.id) }}">Edit</a><br>
 <p>{{ file.path }}</p>
-<img src="/static/uploads/{{ file.path }}" alt="" class="img-thumbnail">
+{% if file.is_image() %}
+<img src="/static/uploads/{{ file.path }}" alt="{{ file.title }}" class="img-thumbnail">
+{% else %}
+<a href="/static/uploads/{{ file.path }}">{{ file.title }}</a>
+{% endif %}
 {% endblock %}