[英]Read a file without saving it locally python/bottle
Hi so basically I have a form that uploads a file嗨所以基本上我有一个上传文件的表格
<input class="btn btn-light" type="file" id="file" name="h" accept=".py">
I'm using bottle, so essentially I want to get the contents of the file but not have to save it locally.我正在使用瓶子,所以基本上我想获取文件的内容,但不必将其保存在本地。 Using with open requires a path which I don't have as it is not saved locally.使用 with open 需要一个我没有的路径,因为它没有保存在本地。
f = request.POST['file']
I get the file using the above.我使用上面的方法获取文件。
Is there any way I could upload the file without having to save it locally?有什么办法可以上传文件而不必在本地保存?
Any help would be much appreciated, I just need the name of the file and the contents.任何帮助将不胜感激,我只需要文件名和内容。
No need to save the file (or to use BytesIO as suggested in a comment).无需保存文件(或按照评论中的建议使用 BytesIO)。 You can simply read its contents:您可以简单地阅读其内容:
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()
Output: Output:
$ 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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.