Python:从request.files获取本地文件路径

2024-06-28 20:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助上传一个文件直接从HTML表单到API。我见过远程URL使用这种方法,但我不知道如何对本地文件使用这种方法?我试着写了这篇文章,但它不起作用:

uploadmedia = request.files['fileupload']
client = Client('thisismykey')
with open(uploadmedia, 'rb') as file:
  new_upload = client.uploads('<space-id>').create(file)

client.uploads是在API文档here中指定的。我只需要能够得到文件路径

评论建议如下:

# you can use either a file-like object or a path.
# If you use a path, the SDK will open it, create the upload and
# close the file afterwards.

我假设request.files['fileupload']是一个类似文件的对象,所以我只是传递了它

上面的代码给出了以下错误:

File "D:\Gatsby\submission\flask-tailwindcss-starter\app\__init__.py", line 28, in index
with open(uploadmedia, 'rb') as file:
TypeError: expected str, bytes or os.PathLike object, not FileStorage

我知道在这个例子中,uploadmedia.filename会得到文件名,但是路径的属性是什么?我该怎么做


Tags: 文件the方法clientapirequestaswith
1条回答
网友
1楼 · 发布于 2024-06-28 20:16:40

request.files['file']FileStorage类的实例。参考api,您不能使用with open(uploadmedia, 'rb') as file:

尝试使用流属性:

uploadmedia = request.files['fileupload']
client = Client('thisismykey')
new_upload = client.uploads('<space-id>').create(uploadmedia.stream)

相关问题 更多 >