File upload at web2py

北战南征 提交于 2019-12-12 03:04:30

问题


I am using the web2py framework. I have uploaded txt a file via SQLFORM and the file is stored in the "upload folder", now I need to read this txt file from the controller, what is the file path I should use in the function defined in the default.py ?

def readthefile(uploaded_file):
    file = open(uploaded_file, "rb")
    file.read()
    ....

回答1:


You can do join of application directory and upload folder to build path to file. Do something like this:

import os

filepath = os.path.join(request.folder, 'uploads', uploaded_file_name)
file = open(filepath, "rb")

request.folder: the application directory. For example if the application is "welcome", request.folder is set to the absolute path "/path/to/welcome". In your programs, you should always use this variable and the os.path.join function to build paths to the files you need to access.

Read request.folder




回答2:


The transformed name of the uploaded file is stored in the upload field of your database table, so you need a way to query the specific record that was inserted via the SQLFORM submission in order to get the name of the stored file. Here is how it would look assuming you know the record ID:

stored_filename = db.mytable(record_id).my_upload_field
original_filename, stream = db.mytable.my_upload_field.retrieve(stored_filename)
stream.read()

When you pass a filename to the .retrieve method of an upload field, it will return a tuple containing the original filename as well as the open file object (called stream in the code above).



来源:https://stackoverflow.com/questions/38001245/file-upload-at-web2py

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!