[英]How to create download button using href - (Flask)?
在我的項目中,我可以將文件保存到目錄中並將其路徑保存到數據庫中。 這是代碼
def save_file(form_file):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_file.filename)
picture_fn = random_hex + f_ext
picture_path = os.path.join(app.root_path, 'static/files', picture_fn)
form_file.save(picture_path)
return picture_fn
@app.route('/ticket/<int:ticket_id>',methods=['GET','POST'])
@login_required
def ticket(ticket_id):
ticket = Tickets.query.get_or_404(ticket_id)
com = Comment.query.filter_by(ticket_id=ticket.id).first()
form = CommentForm()
attachform = AttachForm()
if form.validate_on_submit() and form.body.data:
comment = Comment(body=form.body.data,ticket_id=ticket_id,author = current_user.username)
db.session.add(comment)
db.session.commit()
flash('Your comment has been published.')
return redirect(url_for('ticket', ticket_id=ticket_id))
if attachform.validate_on_submit():
if attachform.file.data:
picture_file = save_file(attachform.file.data)
attachment = Attachment(file=picture_file,ticket_id=ticket_id)
db.session.add(attachment)
db.session.commit()
flash('Your file has been published.')
return redirect(url_for('ticket', ticket_id=ticket_id))
file = url_for('static', filename='files/' + str(ticket.attach))
return render_template('ticket.html', title=ticket.title,file=file ,ticket=ticket,form=form,comment=com,attachform=attachform)
現在我該如何制作,以便當我點擊文件名時它會被下載? 這是我的 html 文件
{% for fil in ticket.attach %}
<ul class="list-group">
<a href="{{ file }}" download class="list-group-item list-group-item-action"> {{ fil }}</a>
</ul>
{% endfor %}
但它下載了一些奇怪的 html 文件而不是實際文件
正如@v25 建議的那樣,我已經創建了一個帶有send_from_directory
燒瓶擴展名的單獨download
函數。
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
uploads = os.path.join(app.root_path, app.config['UPLOAD_FOLDER'])
return send_from_directory(directory=uploads,filename=filename, as_attachment=True)
html文件
{% for file in ticket.attach %}
<ul class="list-group">
<a href="{{ url_for('download', filename=file) }}" download class="list-group-item list-group-item-action"> {{ file }}</a>
</ul>
{% endfor %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.