简体   繁体   中英

File upload at web2py

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()
    ....

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM