【问题标题】:Read a file without saving it locally python/bottle读取文件而不将其保存在本地 python/bottle
【发布时间】:2021-01-13 21:50:37
【问题描述】:

嗨,基本上我有一个上传文件的表单

 <input class="btn btn-light" type="file" id="file" name="h" accept=".py">

我正在使用瓶子,所以基本上我想获取文件的内容,但不必将其保存在本地。使用 with open 需要一个我没有的路径,因为它没有保存在本地。

f = request.POST['file']

我使用上面的方法获取文件。

有什么方法可以上传文件而不必在本地保存?

任何帮助将不胜感激,我只需要文件名和内容。

【问题讨论】:

  • 你在找io.BytesIO

标签: python bottle


【解决方案1】:

无需保存文件(或按照评论中的建议使用 BytesIO)。您可以简单地阅读其内容:

from bottle import Bottle, request

app = Bottle()

@app.post("/upload")
def upload():
    f = request.POST["file_name"]
    text = f.file.read()
    return f"Read {len(text)} bytes from the uploaded file.\n"

app.run()

输出:

$ echo "This is the file to upload." > file.txt
$ curl http://127.0.0.1:8080/upload -F file_name=@file.txt
Read 28 bytes from the uploaded file.

【讨论】:

    猜你喜欢
    • 2020-02-28
    • 1970-01-01
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2016-07-26
    • 2021-10-25
    相关资源
    最近更新 更多