Generate a link with utf-8 values and passing it t

2019-03-05 09:34发布

问题:

How can i ensure that the following html url link is going to return itself with utf-8 encoding?

<meta http-equiv="REFRESH" content="5; URL=http://superhost.gr/files/download?filename={{ filename }}">

As it is now, although the value of filename is being retrieved from Flask as utf-8 it doesn't form the URL link also as utf-8.

Here is how i'm fetching this value and try to use it to download a file.

# Prepare selected file for download...
if request.args:
    filename = request.args.get('filename')         # value comes from template url link
    filepath = '/static/files/'
    return send_from_directory( filepath, filename, as_attachment=True )

I'am trying to generate the link with Jinja2 / Flask under Apache/WSGI mod.

Perhaps Apache under mod_wsgi is causing this issue?!

The error i'am seeing in the browser is:

Bad Request
The browser (or proxy) sent a request that this server could not understand.

The link that is generated according to Chrome's Developer Tool/Network Tab for a a test file with a mixed filename(greek + english) is:

http://superhost.gr/files/download?filename=%CE%94%CE%B7%CE%BC%CE%B9%CE%BF%CF%85%CF%81%CE%B3%CE%AF%CE%B1%20Win10%20Bootable%20Flash%20Disks.txt

回答1:

I'm trying to reproduce your issue but I think that you should provide more information.

I've tried the setup below and the file named Νικόλαος Βέργος.pdf is correctly returned by /redirect/.

app.py

from flask import render_template
from flask import Flask
from flask import request, send_from_directory
app = Flask(__name__)

@app.route('/')
def home():
    filename='Νικόλαος Βέργος.pdf'
    return render_template('home.html', filename=filename)

@app.route('/redirect/')
def redirect():
    if request.args:
        filename = request.args.get('filename')
        filepath = '/static/files/'
        return send_from_directory(filepath, filename, as_attachment=True)

templates/home.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta http-equiv="REFRESH" content="5; URL=http://127.0.0.1:5000/redirect/?filename={{ filename }}">
    <title>title</title>
  </head>
  <body>
  </body>
</html>