我正在学习如何在烧瓶中使用文件上传。早些时候,我处理了pdf文件上传并阅读了其中的内容。这发生在 client.py 文件中。
现在我想将我的文件从客户端传递到本地运行的服务器。当我使用 request.file 时,它会将其作为文件存储对象获取。因此,在不保存或提供文件路径的情况下,我想从客户端上传文件并将其传递给服务器以进行进一步处理。
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)
在这里,我想通过process()
函数将传入文件发送到本地运行的服务器。我该怎么做?我遇到了同样的问题,但找不到任何东西
"提取"是什么意思?如果要获取文件的字节数,可以使用content = request.files['file'].read()
.
然后将此内容发送到您想要的任何位置:res = requests.post(url, content)
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)
如果要从文件存储对象中提取文件,请按照以下步骤操作:通过使用以下代码,您可以从文件存储对象保存文件并将其保存在本地
<!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>