在做flask后端,有个需求是将视频从前端上传至后端,然后再页面播放上传的视频,记录下知识点。
文件流接收
1、前端传来的对象是二进制文件流,有两种方法保存本地。
(1)通过open()方法将文件流写入保存
(2)直接用调用 file.save() 方法保存传来的文件流:
from flask import Flask,request
app = Flask(__name__)
@app.route('/upload',methods = ['POST'])
def file_receive():
# 获取文件对象
file = request.files['file']
# 获取文件名
filename = file.filename
# file.save 也可保存传来的文件
# file.save(f'./{filename}')
with open(f'./{filename}','wb') as f:
f.write(file.stream.read())
return {'success':1}
if __name__ == '__main__':
app.run()
测试该段代码的文件上传可以用requests实现,用open()创建一个二进制对象,传给后端:
import requests
def uploads():
url = 'http://127.0.0.1:5000/upload'
files = {'file':open('C:\\Users\\xxx\\Desktop\\push\\test.mp4','rb')}
r = requests.post(url,files = files)
print(r.text)
if __name__=="__main__":
uploads()
2、如果既要传参数又要传文件呢,用 request.data 可以获取前端传来的参数:
from flask import Flask,request
app = Flask(__name__)
@app.route('/upload',methods = ['POST'])
def file_receive():
# 获取文件对象
file = request.files['file']
# 获取参数body
body = request.data
filename = file.filename
# file.save 也可保存传来的文件
# file.save(f'./{filename}')
with open(f'./{filename}','wb') as f:
f.write(file.stream.read())
return {'success':1}
if __name__ == '__main__':
app.run()
requests 测试代码:
import requests
def uploads():
url = 'http://127.0.0.1:5000/upload'
body = {'info':'test'}
files = {'file':open('C:\\Users\\xxx\\Desktop\\push\\test.mp4','rb')}
r = requests.post(url,json = body,files = files)
print(r.text)
if __name__=="__main__":
uploads()
标签:__,files,name,文件,flask,filename,file,接收,上传 From: https://www.cnblogs.com/shenh/p/17844316.html