How send with a <input type="file"> in a load or ajax - WEB2PY

339 Views Asked by At

Is there any easy way to send files to my controller from a .load view via a input type="file"? Or is there any way to do it with JQuery?

1

There are 1 best solutions below

1
On

By default, forms in Ajax LOAD() components will be trapped and submitted via Ajax. However, the method used for submission will not work for file uploads. Instead, you can override the default behavior by adding a "no_trap" class to the form element and setting up your own form submission handler.

In the view containing the form:

<form id="upload_form" class="no_trap">...</form>

or if the form is generated in a controller:

form = SQLFORM(..., _id='upload_form', _class='no_trap')

In the view containing the component, add an explicit "target" (for later reference):

{{=LOAD('mycontroller', 'myfunction.load', ajax=True, target='upload_form')}}

To handle the file upload, you can use the FormData API. For some ideas, see http://blog.teamtreehouse.com/uploading-files-ajax. You might also consider using a library, such as jQuery File Upload.

Once you have the FormData constructed, you can post to web2py as follows:

$.web2py.ajax_page('post', url, formData, 'upload_form', form)

where url is the URL of the Ajax component, formData is the FormData object you have constructed via your form submission handler, and form is the jQuery form object (i.e., $('form#upload_form')). That will post the form data to the URL and replace the "upload_form" target with the returned HTML.