Check it out: PURE AJAX file uploads :D

94 views
Skip to first unread message

select

unread,
Apr 24, 2013, 11:31:48 AM4/24/13
to web...@googlegroups.com
in your client side js code use the js file api (this is for one file, but multi file upload can be done too)

$('#datafile-uploadfield').change(function() {
   
var upload_element = $(this)[0];
   
var file = upload_element.files[0];
   
if (file) {
     
var reader = new FileReader();
      reader
.readAsDataURL(file); //, "UTF-8");//TODO what encoding should be parsed???
      reader
.onload = (function(theFile) {
       
return function(evt) {
          $
.ajax({
            url
: '{{=URL("datafile_create")}}',
            data
: {
              data
: evt.target.result,
              name
: theFile.name
           
},
            type
: 'POST',
            dataType
: 'json',
            success
: function(data) {
              addDatafile
(data);
           
}
         
});
       
};
     
})(file);
      reader
.onerror = function(evt) {
        alert
(":( oh noo, we could not read your file");
     
};
     
//++counter;
   
}
 
});

in you controller
def datafile_create():
    splitcontents
= request.vars.data.split(',')
   
import base64
    file_content
= base64.b64decode(splitcontents[1])
   
# create file like object
   
import StringIO
    filelike_obj
= StringIO.StringIO(file_content)
    db_store
= db.datafiles.file.store(filelike_obj, request.vars.name)
    record_id
= db.datafiles.insert(file=db_store)


in you db.py
db.define_table('datafiles',
 
Field('file', 'upload', requires=IS_NOT_EMPTY()),
 
)

== PURE AWESOMENESS

Niphlod

unread,
Apr 24, 2013, 11:53:33 AM4/24/13
to web...@googlegroups.com
why the base64 ? I want my files submitted as binaries, if possibile.....

select

unread,
Apr 24, 2013, 12:03:18 PM4/24/13
to web...@googlegroups.com
readAsBinaryString and readAsArrayBuffer and readAsText
did not work, i just tested, but if you have a hint on how to make them work I would be very interested

Niphlod

unread,
Apr 24, 2013, 12:19:09 PM4/24/13
to web...@googlegroups.com
it's not that I don't like the use of native js api, but if the tradeoff is transmitting as base64 that's not an implementation I want to use (given that there are plenty of "drop-loaders" out there).
Base64 the contents means wasting a net 33% of bandwith.

select

unread,
Apr 24, 2013, 12:24:55 PM4/24/13
to web...@googlegroups.com
so what do these drop loaders do to make pure ajax file uploads, i was not aware of that o_O

select

unread,
Apr 24, 2013, 12:46:36 PM4/24/13
to web...@googlegroups.com
so i basically missed what is going on right now because I did not looked at the problem for half a year 
xhr2 is supported by almost all browsers and xhr2 supports sending files :D
implementations are here 
Reply all
Reply to author
Forward
0 new messages