首页 > 解决方案 > 烧瓶'元组'对象在保存文件时没有属性'写'

问题描述

当我想保存在发布请求中收到的文件时,我在烧瓶上收到此有线错误。我尝试调试,但我不明白错误,因为我使用烧瓶保存,在谷歌和其他堆栈溢出问题上,我发现这与 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'

标签: pythonflask

解决方案


我发现了这个问题。我的路径错误,文件名应该在 os.path.join()

file.save((os.path.join(root_dir,'backend', 'upload', filename)))

推荐阅读