Browse Source

[upload] [new design] using filereader and ajax to upload files, no more iframes

version-14
Rushabh Mehta 12 years ago
parent
commit
614ecc59a7
5 changed files with 88 additions and 101 deletions
  1. +1
    -1
      core/page/data_import_tool/data_import_tool.js
  2. +18
    -28
      public/js/wn/form/attachments.js
  3. +55
    -32
      public/js/wn/upload.js
  4. +4
    -11
      webnotes/handler.py
  5. +10
    -29
      webnotes/utils/file_manager.py

+ 1
- 1
core/page/data_import_tool/data_import_tool.js View File

@@ -141,7 +141,7 @@ wn.pages['data-import-tool'].onload = function(wrapper) {
});
// add overwrite option
var $submit_btn = $('#dit-upload-area form input[type="submit"]');
var $submit_btn = $('#dit-upload-area input[type="submit"]');
$('<input type="checkbox" name="overwrite" style="margin-top: -3px">\
<span> Overwrite</span>\
<p class="help">If you are uploading a child table (for example Item Price), the all the entries of that table will be deleted (for that parent record) and new entries will be made.</p><br>')


+ 18
- 28
public/js/wn/form/attachments.js View File

@@ -114,6 +114,7 @@ wn.ui.form.Attachments = Class.extend({
});
},
new_attachment: function() {
var me = this;
if(!this.dialog) {
this.dialog = new wn.ui.Dialog({
title: wn._('Upload Attachment'),
@@ -132,38 +133,27 @@ wn.ui.form.Attachments = Class.extend({
doctype: this.frm.doctype,
docname: this.frm.docname
},
callback: wn.ui.form.file_upload_done
callback: function(fileid, filename) {
me.add_to_file_list(fileid, filename);
me.dialog.hide();
me.refresh();
}
});
},
add_to_file_list: function(fileid, filename) {
var doc = this.frm.doc;
if(doc.file_list) {
var fl = doc.file_list.split('\n');
fl.push(filename + ',' + fileid);
doc.file_list = fl.join('\n');
} else {
doc.file_list = filename + ',' + fileid;
}
},
remove_fileid: function(fileid) {
this.frm.doc.file_list = $.map(this.get_filelist(), function(f) {
if(f.split(',')[1]!=fileid) return f;
}).join('\n');
}
});


// this function will be called after the upload is done
// from webnotes.utils.file_manager
wn.ui.form.file_upload_done = function(doctype, docname, fileid, filename, at_id,
new_timestamp) {
// add to file_list
var doc = locals[doctype][docname];
if(doc.file_list) {
var fl = doc.file_list.split('\n');
fl.push(filename + ',' + fileid);
doc.file_list = fl.join('\n');
} else {
doc.file_list = filename + ',' + fileid;
}
// update timestamp
doc.modified = new_timestamp;
// update file_list
var frm = wn.views.formview[doctype].frm;
frm.attachments.dialog.hide();
msgprint(wn._('File Uploaded Sucessfully.'));
frm.refresh();
};
});

+ 55
- 32
public/js/wn/upload.js View File

@@ -5,44 +5,67 @@
wn.upload = {
make: function(opts) {
var id = wn.dom.set_unique_id();
$(opts.parent).append(repl('<iframe id="%(id)s" name="%(id)s" src="blank.html" \
style="width:0px; height:0px; border:0px"></iframe>\
<form method="POST" enctype="multipart/form-data" \
action="%(action)s" target="%(id)s">\
'+wn._('Upload a file')+':<br>\
<input type="file" name="filedata" /><br><br>\
OR:<br><input type="text" name="file_url" /><br>\
<p class="help">'
+ (opts.sample_url || 'e.g. http://example.com/somefile.png')
+ '</p><br>\
<input type="submit" class="btn" value="'+wn._('Attach')+'" />\
</form>', {
$(opts.parent).append();
var $upload = $("<div class='file-upload'>" + repl(wn._('Upload a file')+':<br>\
<input type="file" name="filedata" /><br><br>\
OR:<br><input type="text" name="file_url" /><br>\
<p class="help">'
+ (opts.sample_url || 'e.g. http://example.com/somefile.png')
+ '</p><br>\
<input type="submit" class="btn btn-info btn-upload" value="'
+wn._('Attach')+'" /></div>', {
id: id,
action: wn.request.url
}));
})).appendTo(opts.parent)
opts.args.cmd = 'uploadfile';
opts.args._id = id;

// get the first file
$upload.find(".btn-upload").click(function() {
// convert functions to values
for(key in opts.args) {
if(typeof val==="function")
opt.args[key] = opts.args[key]();
}
// add request parameters
for(key in opts.args) {
if(opts.args[key]) {
if(typeof val==="function") {
var val = opts.args[key]();
} else {
var val = opts.args[key];
// add other inputs in the div as arguments
$upload.find("input[name]").each(function() {
var key = $(this).attr("name");
if(key!="filedata" && key!="file_url") {
opts.args[key] = $(this).val();
}
$('<input type="hidden">')
.attr('name', key)
.attr('value', val)
.appendTo($(opts.parent).find('form'));
}
})
opts.args.file_url = $upload.find('[name="file_url"]').val();

var fileobj = $upload.find(":file").get(0).files[0];
wn.upload.upload_file(fileobj, opts.args, opts.callback);
})
},
upload_file: function(fileobj, args, callback) {
if(!fileobj && !args.file_url) {
msgprint(_("Please attach a file or set a URL"));
return;
}

var freader = new FileReader();
$('#' + id).get(0).callback = opts.callback
},
callback: function(id, file_id, args) {
$('#' + id).get(0).callback(file_id, args);
freader.onload = function() {
args.filedata = freader.result.split(",")[1];
args.filename = fileobj.name;
var msgbox = msgprint(wn._("Uploading..."));
wn.call({
"method": "uploadfile",
args: args,
callback: function(r) {
msgbox.hide();
if(r.exc) {
msgprint("There were errors in uploading.");
}
callback(r.message, fileobj.name);
}
});
}
freader.readAsDataURL(fileobj);
}
}

+ 4
- 11
webnotes/handler.py View File

@@ -101,25 +101,18 @@ def uploadfile():
import webnotes.utils.file_manager
import json

ret = []

try:
if webnotes.form_dict.get('from_form'):
webnotes.utils.file_manager.upload()
ret = webnotes.utils.file_manager.upload()
else:
if webnotes.form_dict.get('method'):
ret = webnotes.get_method(webnotes.form_dict.method)()
except Exception, e:
webnotes.msgprint(e)
webnotes.errprint(webnotes.utils.getTraceback())
ret = None

webnotes.response['type'] = 'iframe'
if not webnotes.response.get('result'):
webnotes.response['result'] = """<script>
window.parent.wn.upload.callback("%s", %s);
</script>""" % (webnotes.form_dict.get('_id'),
json.dumps(ret))

return ret
@webnotes.whitelist(allow_guest=True)
def reset_password(user):
from webnotes.model.code import get_obj


+ 10
- 29
webnotes/utils/file_manager.py View File

@@ -34,17 +34,12 @@ def upload():
dn = webnotes.form_dict.docname
at_id = webnotes.form_dict.at_id
file_url = webnotes.form_dict.file_url
filename = webnotes.form['filedata'].filename
filename = webnotes.form_dict.filename
webnotes.response['type'] = 'iframe'
if not filename and not file_url:
webnotes.response['result'] = """
<script type='text/javascript'>
window.parent.wn.views.fomrview['%s'].frm.attachments.dialog.hide();
window.parent.msgprint("Please upload a file or copy-paste a link (http://...)");
</script>""" % dt
return
webnotes.msgprint(_("Please select a file or url"),
raise_exception=True)

# save
if filename:
fid, fname = save_uploaded(dt, dn)
@@ -52,24 +47,9 @@ def upload():
fid, fname = save_url(file_url, dt, dn)

if fid:
# refesh the form!
# with the new modified timestamp
webnotes.response['result'] = """
<script type='text/javascript'>
window.parent.wn.ui.form.file_upload_done('%(dt)s', '%(dn)s', '%(fid)s', '%(fname)s', '%(at_id)s', '%(mod)s');
window.parent.wn.views.formview['%(dt)s'].frm.show_doc('%(dn)s');
</script>
""" % {
'dt': dt,
'dn': dn,
'fid': fid,
'fname': fname.replace("'", "\\'"),
'at_id': at_id,
'mod': webnotes.conn.get_value(dt, dn, 'modified')
}
return fid

def save_uploaded(dt, dn):
webnotes.response['type'] = 'iframe'
fname, content = get_uploaded_content()
if content:
fid = save_file(fname, content, dt, dn)
@@ -92,9 +72,10 @@ def save_url(file_url, dt, dn):

def get_uploaded_content():
# should not be unicode when reading a file, hence using webnotes.form
if 'filedata' in webnotes.form:
i = webnotes.form['filedata']
webnotes.uploaded_filename, webnotes.uploaded_content = cstr(i.filename), i.file.read()
if 'filedata' in webnotes.form_dict:
import base64
webnotes.uploaded_content = base64.b64decode(webnotes.form_dict.filedata)
webnotes.uploaded_filename = webnotes.form_dict.filename
return webnotes.uploaded_filename, webnotes.uploaded_content
else:
webnotes.msgprint('No File')
@@ -127,7 +108,7 @@ def save_file(fname, content, dt, dn):
f.file_name = fname
f.attached_to_doctype = dt
f.attached_to_name = dn
f.fize_size = file_size
f.file_size = file_size
f.save(1)

return f.name


Loading…
Cancel
Save