Uploading files using CKEditor in web2py
This is the second part of integrating CKEditor in web2py. I should warn you that quotes are messed up in the blog so you can check at web2pyslices for the updated (and ready for copy-paste) version.
What it needs to be done in order to have ckeditor uploading works. First, it needs a “file browser” url. That’s just a form with an upload field where we can use to find and upload files. The think is that we must return the path of the uploaded file BACK to the parent form. The most difficult part is activating the Upload button. That is done by specifying the “filebrowserBrowseUrl”. So, here it goes!
Let’s add a new table that will hold our files:
import datetime;
timestamp = datetime.datetime.today()
db.define_table('files',
Field('title', 'string'),
Field('uploaded_data', 'upload'),
Field('created_on','datetime',default=timestamp))
db.files.title.requires = IS_NOT_EMPTY()
db.files.uploaded_data.requires = IS_NOT_EMPTY()
Now, lets add an action the our controller
def upload_file():
url = ""
form = SQLFORM(db.files, showid=False)
if form.accepts(request.vars, session):
response.flash = T('File uploaded successfully!')
url = URL(r=request, f="download",
args = db(db.files.title == request.vars.title).select(orderby=~db.files.created_on)[0].uploaded_data)
return dict(form=form, cknum=request.vars.CKEditorFuncNum, url=url)
and a view upload_file.html:
{{extend 'layout.html'}}
<h2>Upload file</h2>
{{=form}}
{{ if url != "": }}
<script type="text/javascript">
window.opener.CKEDITOR.tools.callFunction({{=cknum}}, '{{=url}}');
</script>
{{ pass }}
Then, lets add the javascript files to our layout AFTER web2py_ajax.html:
<script type="text/javascript" src="{{=URL(request.application,'static','js/ckeditor/ckeditor.js')}}"></script>
Finally, lets create a test page:
{{extend 'layout.html'}}
{{=form}}
<script type="text/javascript">
var ckeditor = CKEDITOR.replace('page_body', {
filebrowserBrowseUrl : "{{=URL(request.application, c='default', f='upload_file')}}",
//filebrowserUploadUrl : "{{=URL(request.application, c='default', f='upload_file')}}",
});
</script>
We are ready!