1

I have an API on my Flask server where I may upload a file from a client, using the following code:

@app.route('/api/uploadJob', methods = ['GET', 'POST'])
def uolpadJob():
    try:
        if request.method == 'POST':                
            f = request.files['file']
            fullFilePath = os.path.join(app.config['UPLOAD_FOLDER'],
                secure_filename(f.filename))                    
            #fileSize = ???
            f.save(fullFilePath)

I want to get the file size before to save it in my hard disk, so that I can compare it with the available disk space and chose if i want to save it or to return an error message. How can i get the file size before the actual upload?

Lorenzo
  • 13
  • 3
  • Possible duplicate of [Getting file size in Python?](https://stackoverflow.com/questions/6591931/getting-file-size-in-python) – plalanne Nov 21 '19 at 10:54

1 Answers1

4

This might help if you want to check size details before saving :

@app.route('/api/uploadJob', methods = ['GET', 'POST'])
def uolpadJob():
    try:
        if request.method == 'POST':                
            f = request.files['file']
            fullFilePath = os.path.join(app.config['UPLOAD_FOLDER'],
                secure_filename(f.filename))                    
            f.seek(0, 2)
            file_length = f.tell()
            # Introduce your disk space condition and save on basis of that
            f.save(fullFilePath)

However if you want to checkup after saving the file to your designated path, then try this :

@app.route('/api/uploadJob', methods = ['GET', 'POST'])
def uolpadJob():
    try:
        if request.method == 'POST':                
            f = request.files['file']
            fullFilePath = os.path.join(app.config['UPLOAD_FOLDER'],
                secure_filename(f.filename))                    
            f.save(fullFilePath)
            fileSize = os.stat(fullFilePath).st_size
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
  • 1
    it can also be done that from the user side get the file size through javascript and from the backend, memory allocation size to given can be send to a web interface where it can validated where it is feasible to upload the files or not. – sahasrara62 Nov 21 '19 at 11:01