ใครที่กำลังหาวิธีตรวจสอบนามสกุลไฟล์หรือจะแบ่งนามสกุลไฟล์นะครับ ผมมีวิธีใช้มาแชร์นะครับ ก่อนอื่นเรามารู้จัก ตัว library os ในภาษา Python นะครับ library os คือ จะใช้สำหรับเซื่อมต่อหรือจัดการสิ่งที่เกี่ยวกับระบบปฏิบัติการ ซึ่งในการเรียกใช้งานนั้นต้องทำการ import เข้ามาใช้ครับ รูปแบบการใช้ตัว os.path.splitext() ก็จะมีดังนี้
ทำการ import module os
โค้ด: เลือกทั้งหมด
import os
โค้ดคำสั่งหน้า HTML
โค้ด: เลือกทั้งหมด
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="static/css/datatables.min.css">
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<script src="/static/js/datatables.min.js"></script>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br>
<br>
<div class="container-fluid">
<div class="row">
<div class="col-md-3" ></div>
<div class="col-md-6" >
<div class="card">
<div class="card-header" align="center">Upload File</div>
<div class="card-body">
{%with messages = get_flashed_messages()%}
{%if messages %}
{% for message in messages%}
<div class="alert alert-warning alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Warning! </strong>{{message}}
</div>
{%endfor%}
{% endif %}
{%endwith%}
<form action="/uploaded" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="customFile" name="fileupload">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<div class="mt-3">
<button type="submit" class="btn btn-primary">upload</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-3" ></div>
</div>
</div>
<script>
$(".custom-file-input").on("change", function() {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
</script>
<br>
</body>
</html>
โค้ด: เลือกทั้งหมด
from flask import Flask, render_template,request,flash
import os.path
UPLOAD_FOLDER = '/home/com001/PycharmProjects/test2/uploadfile'
app=Flask(__name__)
app.secret_key = 'ff938fl//jvl;a93kff9qp@Rifomc'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def upload():
return render_template('uploadfile.html')
@app.route('/uploaded', methods=['POST'])
def uploaded():
f = request.files['fileupload']
fileupload = os.path.splitext(f.filename)
if fileupload[1] != '.html':
flash('You incorrect upload file. Try Again')
return render_template('uploadfile.html')
f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
return 'Upload File Success'
if __name__=='__main__':
app.run()
ผลที่ได้ upload file pgadmin.log เข้ามา ปรากฎว่า upload ไม่ได้แต่ลอง upload file html upload file test.html เข้ามา
อ้างอิง
https://www.stackoverflow.com/questions/5899497/checking-file-extension
https://www.docs.python.org/2/library/os.path.html
https://www.geeksforgeeks.org/python-os-path-splitext-method/