Skip to content
Advertisement

Flask – How to get the file extenstion, without using file.content_type

I have this code:

@app.route("/mobile/upload", methods=["POST"])
async def upload_file():
    uploaded_files = await request.files
    uploaded_file = uploaded_files['file']
    uploaded_file_name = generate_name()
    
    fmt = content_type.get(uploaded_file.content_type)
    
    if fmt not in content_type:
        
        return f"That file type is not supported yet ({uploaded_file.filename}{uploaded_file.content_type}), adding now!"
    
    full_name = uploaded_file_name + fmt
    
    await uploaded_file.save("./static/" + full_name)
    return redirect("/static/" + full_name)

And what I would like to do is get the file extenstion, like .md, .txt and automatically add it to the list of allowed content types.

I have looked at the docs but can’t find what I’m looking for.

Heres the content type list:

content_type = {
    "image/png": ".png",
    "image/gif": ".gif",
    "image/jpeg": ".jpeg",
    "text/plain": ".txt",
    "text/html": ".html",
    "audio/mpeg": ".mp3",
    "video/mp4": ".mp4",
    "text/x-generic": ".py",
    "application/x-msdownload": ".exe"
}

Thanks in advance!

Advertisement

Answer

Looking at the comments, it seems your answer is pretty clear.

Just allow any file type and don’t use MIME types.

Thank @Anonymous and @J.G.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement