我嘗試使用 reactjs 和 flask api 每次接收多個檔案,但出現此錯誤
data = file.read()
AttributeError: 'str' object has no attribute 'read'
使用 reactjs 的前端代碼
this.state = {
file : []
}
fileSelectHandler = (event) => {
var totalfiles = event.target.files.length;
for (var index=0; index < totalfiles; index ){
this.state.file.push(event.target.files[index])
}
}
async onFormSubmit (event) {
event.preventDefault();
const formData = new FormData();
formData.append("file", this.state.file);
await fetch(apiUrl 'photo/create' , {
method: 'POST',
body: formData
})
}
使用燒瓶的后端代碼
@app.route('/photo/create', methods=['POST'])
def create_photo():
files = request.form.getlist("file")
print(files)
for file in files:
data = file.read()
燒瓶接收檔案為 ['[object File],[object File]'] 。
我試圖找到讀取目標檔案的方法,但任何人都無法提供任何幫助..
uj5u.com熱心網友回復:
我不使用React,但對我來說問題是
formData.append("file", this.state.file);
因為this.state.file是包含一個或多個檔案的串列,它需要for-loop 將每個檔案作為單獨的物件添加到Form
const formData = new FormData();
var totalfiles = this.state.file.length;
for (var index=0; index < totalfiles; index ){
formData.append("file", this.state.file[index]);
}
現在它發送所有檔案request.files而不是一個(無用的)'[object File],[object File]'字串request.form
最少的作業代碼
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template_string('''
<!DOCTYPE html>
<script>
this.state = {
file: []
}
fileSelectHandler = (event) => {
console.log("fileSelectHandler");
var totalfiles = event.target.files.length;
for (var index=0; index < totalfiles; index ){
this.state.file.push(event.target.files[index]);
}
}
async function onFormSubmit(event) {
console.log("onFormSubmit");
event.preventDefault();
const formData = new FormData();
var totalfiles = this.state.file.length;
for (var index=0; index < totalfiles; index ){
formData.append("file", this.state.file[index]);
}
// doesn't need `http://.../` if sends to the same server
await fetch('/photo/create',
{
method: 'POST',
body: formData,
});
}
</script>
<input type="file" multiple onChange="fileSelectHandler(event);">
<button type="submit" onClick="onFormSubmit(event);">Submit</button>
''')
@app.route('/photo/create', methods=['GET', 'POST'])
def photo():
print('args :', request.args)
print('form :', request.form)
print('json :', request.json)
print('files:', request.files)
for file in request.files.getlist('file'):
print(file.filename)
#print(file.read())
return render_template_string(''' ''')
if __name__ == '__main__':
#app.debug = True
app.run()
uj5u.com熱心網友回復:
@app.route('/photo/create', methods=['POST', 'PUT']) # new
def create_photo():
files = flask.request.form.getlist("file")
print(files) # use loggers
for file in files:
if isinstance(file, str): # check if the file is a string as in path to the file
with open(f"{file}", encoding='utf-8') as f: # read
yield f.read() # yielding is an option but then you need to consume the data differently on the frontend.
我建議閱讀閱讀文本檔案的檔案。如果您正在閱讀影像,那么我們完全在談論其他事情。一些背景關系會更好。
我不想聽起來說教,而是在部署 API 之前對其進行測驗。如果無法選擇測驗,Redoc 或 Swagger 是出色的檔案工具——檔案就足夠了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/420237.html
標籤:
