web2py changes file extension of the uploaded file to txt

94 Views Asked by At

I am using fine-uploader.js and fine-uploader.css for uploading my files using web2py framework.

The callback in the controller is

def upload_callback():
    if 'qqfile' in request.vars:
        filename = request.vars.qqfile
        newfilename = db.doc.filename.store(request.body, filename)
        db.doc.insert(filename=newfilename,uploaded_by=auth.user.id)
    return response.json({'success': 'true'})

The Model

uploadfolder = os.path.join(request.folder, 'uploads')
db.define_table('doc',
    Field('name', requires = IS_NOT_EMPTY()),
    Field('filename', 'upload',autodelete=True,uploadfolder=uploadfolder),
    Field('uploaded_by', db.auth_user)
    )

When I upload file 'test01.xls', web2py stores it in file "doc.filename.bfbf907529358f82.7830302729.txt"

I do not understand why the extension xls is being changed to txt. I have also tried uploading a jpg file. Web2py changes the extension of the uploaded file to txt. Can somebody help me.

1

There are 1 best solutions below

0
Anthony On

As request.vars.qqfile is not the filename but a cgi.FieldStorage object, you cannot use it as the filename but must instead extract the filename from it:

    filename = request.vars.qqfile.filename

Alternatively, you can simply pass the FieldStorage object directly to the .insert method, and web2py will automatically handle extracting the filename and saving the file:

def upload_callback():
    if 'qqfile' in request.vars:
        db.doc.insert(filename=request.vars.qqfile, uploaded_by=auth.user.id)
    return response.json({'success': 'true'})