Home > Mobile >  How to send a pdf file from Flask to ReactJS
How to send a pdf file from Flask to ReactJS

Time:01-06

How can I send a file from Flask to ReactJS?

I have already code that in the frontend, the user upload a file and then that file goes to the Flask server, then in the flask server the file is modify, but I'm stuck there...

The next step is that I want to send that "modify file" that is in the flask server and receive it in the frontend ReactJS so that the user can download the "modify file"

For example, this is the modify file flask function.

#modify the file
@app.route("/convertor", methods=['POST'])
def convertor():
    files = request.files
    #file = files.get('file').read()
    file_name = files.get('file')

    print(file_name.filename)

    # Convert img to pdf
    img1 = Image.open(file_name)
    img = img1.convert('RGB')
    img.save(os.path.abspath(f'Backend/{file_name.filename}.pdf'))

I know it needs to return something, how can I return the file and receive it in ReactJS and then download it?

Any idea?

CodePudding user response:

you will have to download that uploaded file temporarily in a separate director and then

  1. return the url of that file to your React frontend
  2. create a new function to remove that file from the temp directory
@app.route("/remove_file/<file_id>", methods=['DELETE'])
def remove_file(file_id):
    if (os.path.isFile('your_temp_directory/'   file_id)):
       os.remove('your_temp_directory/'   file_id)

edit: you can download from the uploaded file content by using the Wget python package

wget [options eg. multiple files, download speed etc.] -0 dir/path file_url
  •  Tags:  
  • Related