Search code examples
pythonpandasfileflaskfile-upload

Problems with flask when uploading a file and opening with panda


I have a simple flask app. I need to upload a excel file, do some work with it and then save the file on disk. For this purpouse i have this code.


app = Flask(__name__)

FILE_PATH = 'files'
app.config['UPLOAD_FOLDER'] = FILE_PATH

@app.post("/upload")
def upload():
    # Read the File using Flask request
    file = request.files['file']
    
    filename = secure_filename(file.filename)
    
    # Open with panda and do some work.This work don't affect so is no there
    input_df = pd.read_excel(io.BytesIO(file.read()), 'sheetName', header=None)

    # Save the file
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

I have no errors on flask console, but when i go to upload folder i see that uploaded excel file have 0KB and i can't open.

If i don't open with Panda, that is deleting input_df = pd.read_excel(excel_path, 'sheetName', header=None) from the code, all work fine. The uploaded excel file was well.

So my cuestion is what i'm doing wrongo with panda? I need to close after read_excel or something like that? I'm reading flask and pandas documentation but didn't see nothing relted.

Thanks


Solution

  • When you first read the file, the pointer moves within the file to the end. If you then try to save the file, there will be no data left because the pointer has already reached the end.

    If you want to save the file after reading it, it is necessary to move the pointer back to the beginning before saving the file.

    # Open the file with pandas. 
    # ...
    
    file.seek(0)
    
    # Save the file.
    # ...