Download files with accents and non-ASCII letters in the name.

96 views
Skip to first unread message

CarlosDB

unread,
Oct 17, 2022, 2:12:44 PM10/17/22
to py4web

In my applications I usually work with uploaded files and with files generated on the fly.

Many times I need the files to be correctly written in Spanish with accents and other non-ASCII characters.

With the uploaded files, it is currently not possible because when uploading the file, the original name is normalized.

With the files generated on the fly, I want to share what I'm doing and it works fine for me, although I don't know if this solution is valid for all browsers and operating systems.

@authenticated('download_pdf', method=GET)
def download_pdf():

    from pathvalidate import sanitize_filename
    import base64

    pdf = pdf_generator()
    filename = base64.b64encode(nombre_fichero.encode('utf-8')).decode()
    filename = sanitize_filename(filename, '-')
    response.headers['Content-Disposition'] = f'Content-Disposition: attachment; filename="=?UTF-8?B?{filename}?="'
    return pdf

Carlos.

CarlosDB

unread,
Oct 18, 2022, 8:25:59 AM10/18/22
to py4web

The code that I have put is a very simplified copy and paste, but I needed to assign the name of the file.

Here it goes again.

@authenticated('download_pdf', method=GET)
def download_pdf():

    from pathvalidate import sanitize_filename
    import base64

    pdf = pdf_generator()
    pdf_filename = 'áéíóú.pdf'
   
    filename = base64.b64encode(pdf_filename.encode('utf-8')).decode()

    filename = sanitize_filename(filename, '-')
    response.headers['Content-Disposition'] = f'Content-Disposition: attachment; filename="=?UTF-8?B?{filename}?="'
    return pdf

Carlos.

Reply all
Reply to author
Forward
0 new messages