通过使用Flask框架实现一个简单的图片上传工具,当用户提交图片后会自动将图片保存到upload目录下,代码如下
代码语言:javascript复制import os
from flask import Flask, request
import random
import string
import datetime
ALLOWED_EXTENSIONS = set(['rar', 'zip' ,'xls','xlsx','docx','doc','html','png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = "./upload_file" # 将文件上传到当前目录
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024 # 限制只能上传16M的文件
html = '''
<!DOCTYPE html>
<form action="" method="post" enctype="multipart/form-data">
请求序号: {} <br><br>
下单日期: {} <br><br>
接收邮箱: <input type="text" id="email" name="email"><br><br>
需求描述: <textarea rows="5" cols="37" id="my_text" name="my_text" value=""></textarea><br><br>
上传文件: <input type="file" name="file"><br><br>
<b>----------------------------------------</b>
<br> 注: 多个文件请压缩为 .rar .zip 压缩包后上传<br>
<b>----------------------------------------</b><br><br>
<input type="submit" value="提交订单请求">
</form>
'''
ref_html = '''
<b>------------------------------------------------------</b>
<br>您的订单已提交,感谢您的支持 <br>
<b>------------------------------------------------------</b><br><br>
付款订单号: {} <br><br>
接收邮件地址: {} <br><br>
请使用微信支付,并备注该订单号,处理完成后会第一时间邮件发送给您! <br><br>
---> PS图片处理 10元 每张 <br>
---> 打印复印材料 0.5元 每张 -> 宿舍: 3号楼 2层 210自提 <br><br>
<img style="width: 200px;" src="./static/web.jpeg" />
'''
def GenPassword(length):
chars=string.ascii_letters string.digits
return ''.join([random.choice(chars) for i in range(length)])
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'GET':
this_uuid = GenPassword(20)
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
return html.format(this_uuid,now_time)
if request.method == 'POST':
ud = GenPassword(5)
try:
file = request.files.get("file")
email = request.form.get("email")
my_text = request.form.get("my_text")
if file == None or email == None or my_text == None:
return "接口错误"
if file and allowed_file(file.filename):
file.save(os.path.join(app.config['UPLOAD_FOLDER'], "{}_{}".format(ud,file.filename)))
print("*" * 200)
print("订单号: {} ---> 接收邮箱: {} ---> 文件名: {}_{} ---> 需求: {} nn".format(ud,email,ud,file.filename, my_text))
print("*" * 200)
return ref_html.format(ud,email)
except Exception:
pass
return "接口错误"
if __name__ == '__main__':
app.run()