python - 烧瓶'元组'对象在保存文件时没有属性'写'
问题描述
当我想保存在发布请求中收到的文件时,我在烧瓶上收到此有线错误。我尝试调试,但我不明白错误,因为我使用烧瓶保存,在谷歌和其他堆栈溢出问题上,我发现这与 python 文件 API 有关,例如缺少打开或错误标志,但我没有任何标志,或者不需要在这里打开任何文件。
我如何发送文件:
const uploadFile = async (file) =>{
const formData = new FormData();
formData.append("file", file);
fetch("http://localhost:5000/files/upload", {method: "POST", body: formData});
}
我如何接收文件:
@app.route('/files/upload', methods = ['POST'])
def recive_upload_file():
file = request.files['file']
filename = file.filename
root_dir = os.path.dirname(os.getcwd())
file.save((os.path.join(root_dir,'backend', 'upload'), filename))
return "done"
据我所知,文件发送正确,因为如果我尝试在 recive_uploaded_file 函数中打印文件名,我会得到正确的名称。
错误:
Traceback (most recent call last):
File "c:\Python37\lib\site-packages\flask\app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "c:\Python37\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\Python37\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "c:\Python37\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\Python37\lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "c:\Python37\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "c:\Python37\lib\site-packages\flask\app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "index.py", line 239, in upload_file
file.save((os.path.join(root_dir,'backend', 'upload'), filename))
File "c:\Python37\lib\site-packages\werkzeug\datastructures.py", line 3070, in save
copyfileobj(self.stream, dst, buffer_size)
File "c:\Python37\lib\shutil.py", line 82, in copyfileobj
fdst.write(buf)
AttributeError: 'tuple' object has no attribute 'write'
解决方案
我发现了这个问题。我的路径错误,文件名应该在 os.path.join()
file.save((os.path.join(root_dir,'backend', 'upload', filename)))
推荐阅读
- javascript - 我如何使用 javascript/jquery 在枚举中调用函数 js
- node.js - Objection.js 模型的变异器
- ios - 当设备旋转而不将设备锁定为纵向模式时,如何将 collectionView 的所有项目保持在适当的位置?
- javascript - 角度路线是如何构建和处理的?
- javascript - 仅通过复制节点模块无法运行应用程序
- ios - 每次尝试下载 nativescript 插件时都会出错
- javascript - 带有 Postgresql 的 REST API - 如何制作最简单的前端界面
- git - 如何在不引发合并冲突集群****的情况下将子分支分支为具有即将提交和合并的不同开发分支?
- uml - 我无法在理性狂想曲 8.0.1 中将实例规范从浏览器拖到 BDD
- javascript - jquery克隆元素和增量id