26

I am learning how to work with file uploads in flask. Earlier from here, i worked with pdf file uploads and read the contents of it. This happens inside client.py file.

Now i would like to pass my file from client to server that is running locally. When i use request.file, it will get it as FileStorage Object. So, without saving or providing file path, i want to upload file from client and pass it to the server to do further process.

class mainSessRunning():
     def proces(input):
     ...
     ...
     return result

run = mainSessRunning()

@app.route('/input', methods=['POST'])
def input():
    input_file = request.files['file']
   ...(extract file from filestorage object "input_file")...
    result = run.process(file) ## process is user defined function 
    return (result)

here i want to send the incoming file through process() function to server running locally. How do i do this? I came across same question but couldn't able to find anything

dhinar1991
  • 831
  • 5
  • 21
  • 40

2 Answers2

44

What do you mean "extract"? If you want get the bytes of file, you can use content = request.files['file'].read().

And then send this content to any where you want: res = requests.post(url, content)

Sraw
  • 18,892
  • 11
  • 54
  • 87
  • 1
    by Extract i meant, i want to get the input file, for example if i am sending pdf File through POST request.files['file'], i want to get the same pdf file. I don't know if `bytes of file` will help me in this. I Tried file.read() but it throws error : File "/usr/lib/python2.7/genericpath.py", line 26, in exists os.stat(path) TypeError: stat() argument 1 must be encoded string without null bytes, not str ** PS: i dont want contents of the file. i want it as a whole file itself ** – dhinar1991 Apr 17 '18 at 06:28
  • 2
    You definitely can do `content = input_file.read()`. And `content` is absolutely the same as what you get from a local file by `open("your_saved_local_pdf.pdf", "rb").read()`. Is that enough for your purpose? – Sraw Apr 17 '18 at 06:31
  • It's really strange, `os.stat` TypeError usually happen if your file path is invalid such as including `\0`. But as `input_file` is actually a wrapper of a local temp file which is created automatically by flask, this issue shouldn't happen. – Sraw Apr 17 '18 at 06:46
  • I have a similar issue here, could anyone help me?: https://stackoverflow.com/questions/60824889/valueerror-embedded-null-byte-when-using-open-on-pdf-python-flask – rafi Mar 27 '20 at 05:18
  • I am getting "ValueError: I/O operation on closed file." any idea? – MertTheGreat Oct 11 '20 at 19:10
  • as it says the file closed, in my case `i've tried to store the file data in variable` then using it after in another function and it didn't work becuase `i've should've read it there in the main function before the file close cause flask automaticly close file after a return ` or read it there and pass it into another list then use the list – Kamal Zaitar Jun 22 '23 at 15:49
1
import os
import json
from flask import Flask, render_template, url_for, request, redirect, jsonify
from PIL import Image


Upload = 'static/upload'
app = Flask(__name__)
app.config['uploadFolder'] = Upload


@app.route("/")
def index():
    return render_template("Index.html")

@app.route("/upload", methods = ['POST', 'GET'])
def upload():
    file = request.files['imgfile']
    filename = file.filename
    file.save(os.path.join(app.config['uploadFolder'], file.filename))
    print(file.filename)
    img = Image.open(file)
    li = []
    li = img.size
    imgobj = {
    "name" : filename,
    "width" : li[0],
    "height" : li[1]
    }
    json_data = json.dumps(imgobj)
    with open('jsonfile.json', 'w') as json_file:
        json.dump(imgobj, json_file)
    return render_template('index.html', filename = filename) # comment this line to only get the json data.
    # return render_template('index.html', json_data = json_data) # uncomment this line to get only json data.




if __name__ == "__main__":
    app.run(debug = True, port = 4455)

if you want to extract the file from the file storage object please follow the below steps: By using the below code you can save the file from file storage object and save it locally

<!DOCTYPE html>
<html>
<head>
    <title>Assignment</title>
</head>
<body>

{% if filename %}
    <div>
        <h1>{{filename}}</h1>
        <img src="{{ url_for('static', filename='upload/'+filename) }}">
    </div>
{% endif %} <!-- comment this div to only get the json data.-->
<form method="post" action="/upload" enctype="multipart/form-data">
    <dl>
        <p>
            <input type="file" name="imgfile" autocomplete="off" required>
        </p>
    </dl>
    <p>
        <button type="submit" value="Submit"> Submit</button> 
    </p>
</form>
<!-- {% if json_data %}
<div>
    <p> {{ json_data}}
</div>
{% endif %} -->  <!-- uncomment this div to only get the json data.-->

</body>
</html>
  • This is a pretty good answer with a lot of information - but it's written in a slightly messy way that makes it hard to extract all the knowledge :-) – Niels Abildgaard Feb 14 '22 at 11:52