读取文件而不将其保存在本地 python/bottle

问题描述

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

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

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

f = request.POST['file']

我使用上述方法获取文件

有没有什么办法可以上传文件而不必将其保存在本地?

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

解决方法

无需保存文件(或按照评论中的建议使用 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 [email protected]
Read 28 bytes from the uploaded file.