[Python] How to Download a File after POSTing data using FastAPI?

Discussão em 'Python' iniciado por Stack, Dezembro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I am creating a web application that receives some text, converts the text into speech, and returns an mp3 file, which is saved to a temporary directory.

    I want to be able to download the file from the html page (i.e., the frontend), but I don't know how to do that properly.

    I know with Flask you can do this:

    from app import app
    from flask import Flask, send_file, render_template

    @app.route('/')
    def upload_form():
    return render_template('download.html')

    @app.route('/download')
    def download_file():
    path = "html2pdf.pdf"

    return send_file(path, as_attachment=True)

    if __name__ == "__main__":
    app.run()


    HTML Example:

    <!doctype html>
    <title>Python Flask File Download Example</title>
    <h2>Download a file</h2>
    <p><a href="{{ url_for('.download_file') }}">Download</a></p>


    So how do I replicate this with FastAPI?

    FastAPI Code:

    from fastapi import FastAPI, File, Request, Response, UploadFile
    from fastapi.middleware.cors import CORSMiddleware
    from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
    from fastapi.templating import Jinja2Templates
    from gtts import gTTS

    templates = Jinja2Templates(directory="templates")


    def text_to_speech(language:str, text: str) -> str:
    tts = gTTS(text=text, lang=language, slow=False)
    tts.save("./temp/welcome.mp3")
    #os.system("mpg321 /temp/welcome.mp3")
    return "Text to speech conversion successful"


    @app.get("/")
    def home(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

    @app.get("/text2speech")
    async def home(request: Request):
    if request.method == "POST":
    form = await request.form()
    if form["message"] and form["language"]:
    language = form["language"]
    text = form["message"]
    translate = text_to_speech(language, text)
    path = './temp/welcome.mp3'
    value = FileResponse("./temp/welcome.mp3", media_type="audio/mp3")
    return value
    # return templates.TemplateResponse(
    # "index.html",
    # {"request": request, "message": text, "language": language, "download": value},
    # )



    Sample HTML File:

    <!doctype html>
    <title>Download MP3 File</title>
    <h2>Download a file</h2>
    <p><a href="{{ url_for('text2speech') }}">Download</a></p>

    Continue reading...

Compartilhe esta Página