问题
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 theos.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