开发者

Post Binary Sting to Django app using HTML 5

开发者 https://www.devze.com 2023-01-20 04:04 出处:网络
I read in a file via HTML5 FileReader and jQuery like so: holder.ondrop = function(e) { this.className = \'\';

I read in a file via HTML5 FileReader and jQuery like so:

holder.ondrop = function(e) {
    this.className = '';
    e.preventDefault();

    var file = e.dataTransfer.files[0],
    reader = new FileReader();

    reader.onloadend = function(event) {
        $.ajax({  
        url:"/path/to/upload",
        type: "POST",  
        data: event.target.result, 
        success: function(data, status, xhr) {
         alert("success!");
        },
        error: function(xhr, status, error) {
         alert("fail")
        },
        });
    };

    reader.readAsBinaryString(file);
    return false;
};

The "ondrop" is used to handle drag and drop on an element i've named "holder".

The file is submitted to my django app, and if I simply

print request.raw_post_data

I see binary output in my console.

I try to write this to a file like so (yes in my test it's always a jpg):

f = open('/tmp/file.j开发者_开发技巧pg', 'wb')
f.write(request.raw_post_data)
f.close()

And the file is written but when I try to open it, it seems corrupted.

My suspicion is that it has something to do with request.raw_post_data getting incorrectly encoded but i'm not exactly sure how to correct it ... raw_post_data looks like binary although type() returns str.

Any thoughts?


this post was really helpful for me, maybe it will be helpful for you too

http://hacks.mozilla.org/2010/06/html5-adoption-stories-box-net-and-html5-drag-and-drop/

I ended up changing my javascript to be:

holder.ondrop = function(e) {
        e.preventDefault();

        var file = e.dataTransfer.files[0];
        var request = new XMLHttpRequest();

        request.open("POST",  upload_url, true); // open asynchronous post request
        request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        request.send(file);        
    };

and voila.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号