Skip to content Skip to sidebar Skip to footer

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 i

Solution 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


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


Post a Comment for "File Upload At Web2py"