我正在尝试使用Ajax POST请求将图像文件作为FormData发送。
我面临两个问题:
- 我不知道如何在Flask部分提取FormData
- 当进行Ajax POST请求时,我会遇到500内部服务器错误(不确定是否是因为问题1)
谢谢
Flask Python代码:
@app.route('/', methods=['GET','POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file: # and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(os.getcwd()+"/static", "current_image.jpg"))
return jsonify({'tasks': tasks})
HTML和Javascript代码:
<input id="pictureInput" type=file name=file>
<input type=submit value=Upload id="button">
<script type="text/javascript">
var pictureInput = document.getElementById("pictureInput");
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$("#button").click(function(){
console.log(pictureInput);
console.log(pictureInput.files[0]);
console.log(myFormData);
$.ajax({
url: "http://localhost:8000/",
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData,
success : function(data){
console.log(data);
},
});
});
</script>
错误:
![输入图像描述](https://istack.dev59.com/yiAgd.webp)
sys.stdout.write
上。 - Daniel Roseman