Upload a file from Flutter, process it in rest API and then download send it to Flutter

Viewed 40

im trying to create a communication between flutter and a flask rest API. I wanted to send a file from Flutter(epub file) to the API, then process it to txt and finally re-send it to flutter. The problem is that i don't want to create the html box for the uploading part of the file, for ux and ui of the app, so making it easier for the user. In the server part i use some epub files example in local, so that from chrome i do a get request and all works fine, but i dont know how to upload a file from Flutter app to Flask.

This is the Flask part =

from flask import Flask,send_file,send_from_directory, flash, request, redirect, 
url_for
from werkzeug.utils import secure_filename
import ebooklib
from ebooklib import epub
from bs4 import BeautifulSoup
import os


#//////////////////////////////----epub to txt------///////////////////////////////////

def epub2thtml(epub_path):
    book = epub.read_epub(epub_path)
    chapters = []
    for item in book.get_items():
        if item.get_type() == ebooklib.ITEM_DOCUMENT:
            chapters.append(item.get_content())
    print(chapters)
    return chapters
blacklist = [   '[document]',   'noscript', 'header',   'html', 'meta', 'head','input', 'script',   ]

def chap2text(chap):
    output = ''
    soup = BeautifulSoup(chap, 'html.parser')
    text = soup.find_all(text=True)
    for t in text:
        if t.parent.name not in blacklist:
            output += '{} '.format(t)
    return output
def thtml2ttext(thtml):
    Output = []
    for html in thtml:
        text =  chap2text(html)
        Output.append(text)
    return Output
def epub2text(epub_path , nomefile):
    chapters = epub2thtml(epub_path)
    ttext = thtml2ttext(chapters)
    #print (ttext)
    a = 0;
    s = ' ';
    
    with open(nomefile, 'w') as f:
        b = s.join(ttext)
        testo = b.split()
        for i in testo:
            f.write(testo[a])
            f.write('\n')
            a = a + 1;
        print(testo)
    f.close()

#//////////////////////////////----server------///////////////////////////////////


app = Flask(__name__)
app.config["CLIENT_EPUB"] = "...../libri"
@app.route('/epub/<string:epubfilename>',methods = ['GET','POST'])
def get_txt(epubfilename):
    nometxt = str(os.path.splitext(epubfilename)) + ".txt"
    epub2text(epubfilename, nometxt)
    try:
        return send_from_directory(app.config["CLIENT_EPUB"], nometxt, as_attachment=True)
    except FileNotFoundError:
        abort(404)
        
if __name__ == '__main__':
   app.run(debug = True, port=2500)

  

For the flutter part i wanted to use a multipart request to do some of these requests, an example=

void sendRequest() {
    var request = MultipartRequest();
    final imagePath = ('assets/testo.txt');
    request.setUrl(...url);
    request.addFile("text", imagePath);

    Response response = request.send();

    response.onError = () {
      print("Error");
    };

    response.onComplete = (response) {
      print(response);
    };

    response.progress.listen((int progress) {
      print("progress from response object " + progress.toString());
    });
  }

How can i upload the file from the app to the api without the form and resend it? Thanks in advance, i think it isnt that difficult but i cant!

0 Answers
Related