I want to upload file with SQL.factory()
I would just like to maintain the original filename
my code currently is
form = SQLFORM.factory(
Field('file_name', requires=IS_NOT_EMPTY()),
Field('file', 'upload',uploadfolder=upload_folder))
if form.accepts(request.vars, session): #.process().accepted:
response.flash = u'File uploaded'
session.your_name = form.vars.file_name
session.filename = request.vars.file
elif form.errors:
response.flash = 'form has errors'
return dict(form=form)
I guess session.filename = request.vars.file is where you set file name. Why do i get the autogenerated file name no_data.smth.23u8o8274823zu4i2.smth
Thank you
First,
request.vars.fileis a Pythoncgi.FieldStorageobject, sosession.filename = request.vars.fileshould result in an error.request.vars.file.fileis the actual file object, andrequest.vars.file.filenameis the original name of the uploaded file.When you upload a file via an upload field, web2py automatically generates a new name of the form ‘table_name.field_name.random_id.b16encoded_original_filename.extension’. This is done to prevent directory traversal attacks and to enable the download mechanism (which needs to know the table and field name). In the case of SQLFORM.factory, there is no database table name, so it defaults to a table name of ‘no_table’.
The code you have shown should not actually generate a filename like ‘no_data.smth.23u8o8274823zu4i2.smth’. That filename implies you have explicitly told
SQLFORM.factoryto use a table name of ‘no_data’ (via itstable_nameargument) and that the upload field name is ‘smth’. (The code above would generate a filename starting with ‘no_table.file’.)Note, web2py automatically obtains the original name of the uploaded file and encodes it (using b16encode) into the new filename (it then decodes the original filename when the built-in download mechanism is used). The original filename is also available in form.vars.file.filename. So, you don’t necessarily need the user to enter a filename at all. However, if you want to enable the user to enter a filename that may differ from the actual filename and then use the user-entered filename, you can add the following before the form creation:
That will re-assign the filename of the uploaded file to the value entered by the user, and web2py will then encode that user-entered filename into the new filename. Note, however, that web2py relies on the filename extension to set the HTTP headers appropriately upon download, so you may want to add some logic to obtain the original filename extension in case the user fails to enter it.